Merge parity-base into parity/spawn-gear
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+22
-15
@@ -8,12 +8,7 @@ permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
verify:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Linux only. macOS only when started by hand: gh workflow run checks --ref <branch>.
|
||||
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["ubuntu-latest", "macos-26"]' || '["ubuntu-latest"]') }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -27,14 +22,30 @@ jobs:
|
||||
python tools/check_public_tree.py --history
|
||||
- name: Test offline research tooling
|
||||
run: python -m unittest discover -s tests -v
|
||||
- name: Install Rust toolchain
|
||||
run: rustup toolchain install stable --profile minimal --component rustfmt --component clippy
|
||||
- name: Install Rust toolchain and the ALSA headers the client's audio links against
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev
|
||||
rustup toolchain install stable --profile minimal --component rustfmt --component clippy
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo +stable fmt --all -- --check
|
||||
cargo +stable clippy --workspace --all-targets -- -D warnings
|
||||
- name: Test Rust core and voxel kernel correctness
|
||||
run: cargo +stable test --workspace
|
||||
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
|
||||
# (label horizon-game) holding the maintainer's own copy: the official launcher's
|
||||
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
|
||||
# HORIZON_SERVER_JAR. Start them by hand: gh workflow run checks --ref <branch>.
|
||||
vanilla-parity:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: [self-hosted, linux, horizon-game]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Install Rust toolchain
|
||||
run: rustup toolchain install stable --profile minimal
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
@@ -374,12 +385,8 @@ jobs:
|
||||
RUSTUP_TOOLCHAIN: stable
|
||||
run: python tools/test_float_log_parity.py
|
||||
portable-mod:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Linux only. macOS only when started by hand: gh workflow run checks --ref <branch>.
|
||||
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["ubuntu-latest", "macos-26"]' || '["ubuntu-latest"]') }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: [self-hosted, linux, horizon-game]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
@@ -466,7 +473,7 @@ jobs:
|
||||
- name: Upload original mod and pack manifests only
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: horizon-${{ matrix.os }}
|
||||
name: horizon-linux
|
||||
path: |
|
||||
dist/*.mrpack
|
||||
dist/horizon-*.jar
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
name: release builds
|
||||
# Started by hand: gh workflow run release.yml --ref <branch>
|
||||
# Builds the Windows x64 client and uploads the playable folder as an artifact.
|
||||
# Linux and macOS builds are made on the development machines.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust toolchain
|
||||
run: rustup toolchain install stable --profile minimal
|
||||
- name: Build the client
|
||||
# The C runtime linked in, so the game runs without the Visual C++ redistributable.
|
||||
env:
|
||||
RUSTFLAGS: -C target-feature=+crt-static
|
||||
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client
|
||||
- name: Package
|
||||
shell: bash
|
||||
run: packaging/package.sh target/release/horizon-client.exe dist/horizon-windows-x64
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: horizon-windows-x64
|
||||
path: dist/horizon-windows-x64
|
||||
@@ -1,337 +1,199 @@
|
||||
<p align="center">
|
||||
<img src="docs/media/banner.jpg" alt="Horizon: Minecraft Java Edition 26.3, rewritten from scratch in Rust" width="100%">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/ludovic111/horizon/actions/workflows/ci.yml"><img src="https://github.com/ludovic111/horizon/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>
|
||||
<img src="https://img.shields.io/badge/Minecraft-Java%2026.3-5D9C3F" alt="Minecraft Java 26.3">
|
||||
<img src="https://img.shields.io/badge/Rust-stable-B7410E?logo=rust&logoColor=white" alt="Rust">
|
||||
<img src="https://img.shields.io/badge/vanilla%20parity-88%25-F0795A" alt="Vanilla parity 88%">
|
||||
<img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-2A2470" alt="Linux, macOS and Windows">
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-3B2F7E" alt="MIT license"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#getting-it"><b>Get started</b></a> ·
|
||||
<a href="#screenshots"><b>Screenshots</b></a> ·
|
||||
<a href="#project-status"><b>Parity status</b></a> ·
|
||||
<a href="docs/native-client.md"><b>Native client guide</b></a>
|
||||
</p>
|
||||
|
||||
# Horizon
|
||||
|
||||
Horizon is a Rust rewrite of Minecraft Java **26.3** targeting one-to-one vanilla gameplay parity, alongside client performance research. Not affiliated with Mojang or Microsoft.
|
||||
A Rust rewrite of Minecraft: Java Edition 26.3 that aims for one-to-one vanilla parity, checked against the game itself with differential tests.
|
||||
|
||||
**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 88% (see [Project status](#project-status)).
|
||||
|
||||
> Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. Horizon contains no Minecraft code, assets or data: you need your own legally obtained copy of Minecraft: Java Edition 26.3.
|
||||
|
||||
## Screenshots
|
||||
|
||||
Captured in the Rust client itself, with vanilla assets and no mods or shaders.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="2"><img src="docs/media/sunset.jpg" alt="Sunset over a savanna river valley and a plains village"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/village.jpg" alt="A plains village with farms, an iron golem and animals"></td>
|
||||
<td width="50%"><img src="docs/media/survival.jpg" alt="Survival at dusk: a zombie attacks near the village"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/nether.jpg" alt="A crimson forest in the Nether with a zombified piglin"></td>
|
||||
<td width="50%"><img src="docs/media/night.jpg" alt="Moonrise over a torch-lit village and river"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/underwater.jpg" alt="Salmon swimming in a river"></td>
|
||||
<td width="50%" valign="middle">
|
||||
Vanilla world generation ported to Rust (terrain, aquifers, carvers, features, villages and the Nether), every block model with smooth lighting and biome tints, the vanilla sky and fog, mobs, the HUD, chat and advancements: everything in these frames is drawn by Horizon.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## What it does
|
||||
|
||||
Horizon reimplements the Minecraft Java client and its game logic in Rust, one subsystem at a time, and compares each piece with the vanilla game. Each `tools/test_*_parity.py` harness drives the same inputs through Horizon and through the vanilla client and server bytecode from your own copy of the game, then checks that the outputs are identical. It is for players and developers interested in game reimplementation, and for anyone who wants to see how far a behaviour-exact native rewrite can go.
|
||||
|
||||
The [native client](docs/native-client.md) opens on a vanilla-style title screen with world creation and selection, and generates worlds with the Rust port of the vanilla generators: noise terrain, aquifers, surface rules, carvers and placed features, all checked against vanilla. It streams and lights chunks on worker threads and renders every vanilla block model with smooth lighting, biome tints, the vanilla sky, sun, moon, stars and clouds. Gameplay includes:
|
||||
|
||||
**The Rust game is now playable.** The [native client](docs/native-client.md) opens on a vanilla-style title screen with world creation and selection, and generates worlds with the Rust port of the vanilla overworld generator: noise terrain, aquifers, surface rules, carvers, and the placed features ported so far, all checked against vanilla. It streams and lights chunks on worker threads and renders every vanilla block model with smooth lighting, biome tints, the vanilla sky, sun, moon, stars and clouds. Gameplay so far:
|
||||
- validated player physics, health and hunger;
|
||||
- mining with vanilla tool rules and loot tables;
|
||||
- placing, crafting, chests and furnaces;
|
||||
- dropped items and particles;
|
||||
- sounds;
|
||||
- passive and hostile mobs with combat, including guardians, shulkers, illagers, ravagers, the wither and the ender dragon fight;
|
||||
- villagers that take jobs, trade, restock, meet at the bell and sleep in beds;
|
||||
- dropped items, particles and sounds;
|
||||
- passive and hostile mobs with combat and vanilla AI, including guardians, shulkers, illagers, ravagers, the wither, the ender dragon fight, the breeze, the creaking, the sniffer, the happy ghast, llamas and the copper golem;
|
||||
- villagers that take jobs, trade, restock, meet at the bell and sleep in beds, on a port of vanilla's brain;
|
||||
- raids and pillager patrols;
|
||||
- dispensers, crafters, the loom and the recipe book;
|
||||
- every command, scoreboards and teams, the player list, subtitles and the HUD overlays;
|
||||
- boats, minecarts, item frames, paintings and armor stands;
|
||||
- shields, maps, books, fireworks, beacons, advancements and statistics;
|
||||
- Anvil saves.
|
||||
- Anvil saves, joining vanilla servers, and opening a world to LAN.
|
||||
|
||||
Parity is **not** complete. Still missing: the warden and the sculk family, the breeze, sniffer, creaking, happy ghast, llamas and a few other mobs, raids and pillager patrols, villager breeding and gossip, the loom, crafter and recipe book, scoreboards, subtitles, and spawned mob gear enchantments. Multiplayer joins vanilla servers but Horizon cannot host one. See [Rust rewrite status](docs/rust-parity.md).
|
||||
## Getting it
|
||||
|
||||
### Java parity: 84%
|
||||
Builds for **Linux x86-64**, **macOS Apple Silicon** and **Windows x64** are attached to the [releases](https://github.com/ludovic111/horizon/releases). Each folder holds the game, the resource preparation tool and a `PLAY.txt`; the first start prepares the resources from your own copy of the game, as below. You can also build from source.
|
||||
|
||||
**Platform.** A GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Development and the vanilla harnesses run on Linux.
|
||||
|
||||
**Requirements.** Python 3.10 or newer and JDK 25 (for resource preparation). To build from source: Rust 1.90 or newer, and on Linux the ALSA development headers (`libasound2-dev` on Debian and Ubuntu).
|
||||
|
||||
### Bring your own copy
|
||||
|
||||
Horizon contains no game files and never downloads them. It builds its resources from **your own copy** of Minecraft: Java Edition 26.3, verified against the checksums in `research-lock.json`:
|
||||
|
||||
1. **Client:** install Java Edition with the official launcher and play 26.3 once. Horizon reads `versions/26.3/`, `libraries/` and `assets/` from the launcher's game directory (`~/.minecraft` on Linux). If yours lives elsewhere, pass `--minecraft-dir` or set `HORIZON_MINECRAFT_DIR`.
|
||||
2. **Server jar:** download the 26.3 server jar yourself, from [minecraft.net/download/server](https://www.minecraft.net/en-us/download/server) while 26.3 is the current release, or otherwise from the `downloads.server.url` in your launcher's `versions/26.3/26.3.json`. Pass it with `--server-jar` or set `HORIZON_SERVER_JAR`. It is only needed the first time.
|
||||
|
||||
### Build and run
|
||||
|
||||
```sh
|
||||
git clone https://github.com/ludovic111/horizon.git
|
||||
cd horizon
|
||||
python3 tools/prepare_native_client.py --prepare --server-jar ~/Downloads/server.jar # needs JDK 25
|
||||
python3 tools/fetch_sounds.py # optional: sounds from your launcher install
|
||||
cargo run --release -p horizon-client
|
||||
```
|
||||
|
||||
Everything prepared lands in the gitignored `.local/`. It is derived from the game: never commit it or share it.
|
||||
|
||||
## Usage
|
||||
|
||||
The client starts on the title screen. Command-line options (`--world`, `--seed`, `--creative`, `--render-distance`), controls, scripting through `horizon-ctl`, and packaging for another of your own Linux machines are described in [the native client guide](docs/native-client.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Native client](docs/native-client.md): running, options, controls, scripting and architecture.
|
||||
- [Rust rewrite status](docs/rust-parity.md): completion criteria and per-area scope.
|
||||
- Parity notes: [block behaviours and ticking](docs/parity/blocks.md), [section meshing](docs/parity/meshing.md).
|
||||
- [Decompilation and Rust research lab](docs/research-lab.md): the local game inspection workspace and the first research crates.
|
||||
- [Decompilation status](docs/decompilation-status.md).
|
||||
- [Java performance packs](docs/java-packs.md): the earlier, no longer developed Java track.
|
||||
|
||||
## Project status
|
||||
|
||||
Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, spawned mob gear enchantments, the resource pack screen, a dedicated server mode, and worlds older than 1.17.
|
||||
|
||||
### Java parity: 88%
|
||||
|
||||
Each subsystem scores 0 (absent), 0.25 (started, not playable), 0.5 (playable,
|
||||
major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete
|
||||
and verified against vanilla by differential tests). The percentage is the
|
||||
average; `tests/test_parity.py` keeps it in sync with this table. Last audited
|
||||
2026-10-10 against the code, not the docs. The harnesses that failed in the
|
||||
previous audit (block updates, random ticks, redstone, command parsing, menu
|
||||
clicks, whole chunks, entity models and item models) now pass; the save
|
||||
round-trip harness has not been rerun.
|
||||
2026-10-12 against the harness results: 270 harnesses pass. Two still differ
|
||||
from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and
|
||||
`sculk` (427 of 435; shrieker warnings and warden summoning).
|
||||
|
||||
| Subsystem | Score | Main gaps |
|
||||
| --- | ---: | --- |
|
||||
| Window, input and game loop | 0.75 | Game loop and options match vanilla; camera, auto-jump, toggle sprint/sneak and the frame limiter not compared |
|
||||
| Assets and resources | 0.75 | Item models match vanilla over 196,290 stacks, but the client does not draw items through that pipeline yet; no pack screen |
|
||||
| Network protocol and multiplayer | 0.75 | Opens worlds to LAN, but hosting is not tested against a vanilla client; no dedicated server mode |
|
||||
| Window, input and game loop | 1 | None: the game loop, options, camera, auto-jump, toggle sprint/sneak, local input and the frame limiter match vanilla |
|
||||
| Assets and resources | 0.75 | Item models match vanilla over 196,290 stacks and the client draws every item through them; no resource pack screen |
|
||||
| Network protocol and multiplayer | 0.75 | Joins vanilla servers and opens worlds to LAN; server.properties, eula.txt and the user lists match vanilla, but there is no dedicated server mode and LAN hosting is not tested against a vanilla client |
|
||||
| Chunk storage and palettes | 1 | None: client and saves share paletted containers, identical to vanilla over 266 scenarios |
|
||||
| Section meshing | 1 | None: 112 scenes and over a million quads identical to vanilla |
|
||||
| Rendering | 0.75 | Entity models match over 150 layers; block entity renderers and HUD overlays not compared |
|
||||
| Rendering | 0.75 | Entity models, block entity renderers (400 cases, End portals and gateways included) and their animations (256 cases), the HUD overlays (2,200 states), the player list, subtitles and the world border match vanilla; the recipe book's drawing and the banner preview are not compared, and End gateways show no beam in game |
|
||||
| Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included |
|
||||
| World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla |
|
||||
| Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.18.2 to 26.2 upgrade as vanilla's DataFixers do over 22 sample worlds; worlds older than 1.18.2 are not upgraded |
|
||||
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules and natural spawning (15,500 NaturalSpawner cases) match; AI not compared; drowned, villagers, traders and the wither unverified |
|
||||
| Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences |
|
||||
| Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering |
|
||||
| Audio | 0.75 | Sound engine, music and ambience not compared with vanilla |
|
||||
| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone and dispensers match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems |
|
||||
| Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded |
|
||||
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing |
|
||||
| Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla |
|
||||
| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), and the player list matches over 844,758 draw calls; the focused chat is not compared and player list heads use default skins |
|
||||
| Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla |
|
||||
| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers (6,000 cases), crafters (4,000 crafts) and block entity removal (containers spill, 4,000 cases) match vanilla; 8 of 435 sculk scenarios differ (shrieker warnings and warden summoning) and the copper golem's chest sorting is not compared |
|
||||
|
||||
### Next steps
|
||||
### What's new since the previous version
|
||||
|
||||
1. Upgrade saves older than 1.18.2 (the DataFixers before DataVersion 2970).
|
||||
2. Draw every item through the item model pipeline, and add the resource pack screen.
|
||||
3. An audio harness: sound engine attenuation, weighted sound events, music and ambience.
|
||||
4. A mob AI harness, and an oracle for drowned, villagers, traders and the wither.
|
||||
5. The missing commands, containers spilling when replaced, copper golems, the tab list and world border rendering.
|
||||
6. Test LAN hosting with a vanilla client, and add a dedicated server mode.
|
||||
- **Mob AI matches vanilla**, compared tick by tick in 72 scenarios, with villagers on a port of vanilla's brain (memories, sensors, schedules and behaviours).
|
||||
- **New mobs:** the breeze and wind charges, the creaking and the creaking heart, the sniffer, the happy ghast and ghastlings, llamas and trader llamas, and the copper golem; the warden's model, animations and emissive layers.
|
||||
- **Raids and pillager patrols**, with the Raid Omen, the waves and the Hero of the Village effect.
|
||||
- **Dispensers, crafters, the loom and the recipe book**, and containers spill their items when their block is replaced.
|
||||
- **Every command runs as vanilla**, including /item modify, /spectate, /waypoint, /dialog and /place.
|
||||
- **Scoreboards and teams** in gameplay (criteria, friendly fire, collision, name tags), the **player list**, **subtitles**, every **HUD overlay**, **block entity animations** (chests, shulker boxes, bells, conduits, heads, the enchanting table's book) and **End portals and gateways** drawn with vanilla's shader.
|
||||
- **Worlds from 1.17 onwards** open and are upgraded as vanilla does; server.properties, eula.txt and the server user lists are read and written as vanilla does.
|
||||
- **Builds for Linux, macOS (Apple Silicon) and Windows.**
|
||||
|
||||
### Known issues
|
||||
|
||||
- **Render distance 2 never finishes loading:** a world opened with the render distance at 2 chunks stays on "Loading terrain…". Use a render distance of 3 or more (in Options > Video, or `--render-distance 12` on the command line).
|
||||
|
||||
### Roadmap
|
||||
|
||||
1. Fix loading at render distance 2; finish the warden's brain and the sculk shrieker summoning it, and the tempted ghastling.
|
||||
2. Villager breeding and gossip, and spawned mob gear enchantments (both started on their branches).
|
||||
3. A dedicated server mode, and LAN hosting tested with a vanilla client.
|
||||
4. Save upgrades from before 1.17, and the resource pack screen.
|
||||
5. Platform-independent float math, so every harness also gives vanilla's results on macOS.
|
||||
|
||||
The rewrite is complete when it reaches one-to-one parity and packaged native builds pass the launch checks in [Rust rewrite status](docs/rust-parity.md#completion-criteria-and-playable-builds).
|
||||
|
||||
### After the rewrite
|
||||
|
||||
Once Horizon matches vanilla, the plan is to build on that exact base:
|
||||
|
||||
- **Performance:** optimize the client and the server as far as they can go (rendering, chunk generation and meshing, memory, multithreaded ticking) while the differential harnesses keep gameplay identical to vanilla.
|
||||
- **Modding support:** a stable API for writing mods against Horizon.
|
||||
- **Agent control:** an MCP server and a CLI so AI agents and scripts can play and drive the game, growing out of today's `horizon-ctl` scripting socket.
|
||||
- **Built-in recording:** capture gameplay video in a keypress, without external tools.
|
||||
- **Automatic version updates:** a pipeline that ports each new Minecraft release on its own: compare the new version with the pinned one, regenerate the data, rewrite the changed parts and prove them with the same differential harnesses.
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and pull requests are welcome. Before opening a pull request, run the offline checks:
|
||||
|
||||
```sh
|
||||
python3 tools/prepare_native_client.py --prepare # needs JDK 25; extracts private vanilla resources
|
||||
python3 tools/fetch_sounds.py # optional: vanilla sounds
|
||||
cargo run --release -p horizon-client
|
||||
```
|
||||
|
||||
**Target machine:** the Rust rewrite targets one machine, **ludodesktop**: Ubuntu 26.04, Intel i7-13700KF, NVIDIA RTX 4080, GNOME on Wayland. The final deliverable is a playable native Linux build validated there. macOS (including the M2 Pro Mac) and Windows are out of scope. Track implementation and acceptance criteria in [Rust rewrite status](docs/rust-parity.md).
|
||||
|
||||
**Java performance packs (no longer developed):** the earlier track of pinned Java performance packs, distant terrain, an original frame/tick recorder and client/server starter downloads. No release downloads are published; build the packs and starters locally with `python3 tools/build_release.py` (see [Build and run](#build-and-run)). They are no longer a development target.
|
||||
|
||||
## Java packs: Mac starter (out of scope)
|
||||
|
||||
Build **horizon-mac-starter-0.21.0.zip** with `python3 tools/build_release.py` (it lands in `dist/`), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials.
|
||||
|
||||
Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on your 16 GB M2 Pro. Prism can download Java automatically. Start at 1280×800 or 1920×1200; full Retina resolution is a larger GPU workload. [START-HERE.txt](packs/START-HERE.txt) has details. The same `.mrpack` files import into Prism on Windows and Linux.
|
||||
|
||||
If Prism is already installed, follow the [Mac import and first comparison guide](docs/mac-first-test.md).
|
||||
|
||||
Core and balanced also pass [macOS title/demo-world rendering probes](docs/client-graphics-smoke.md)
|
||||
on the hosted ARM64 software renderer, including readback, saves and clean exits.
|
||||
Physical M2 GPU performance and macOS 27 remain to be tested.
|
||||
|
||||
| Profile | Full-detail chunks | Distant LOD radius | Suggested maximum heap |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| baseline | 12 | none | 6144 MiB |
|
||||
| core-performance | 12 | none | 6144 MiB |
|
||||
| m2-balanced | 12 | 128 | 6144 MiB |
|
||||
| adaptive (experiment) | 12 | 128 | 6144 MiB |
|
||||
| worker-pacing (experiment) | 12 | 128 | 6144 MiB |
|
||||
| adaptive-pacing (experiment) | 12 | 128 | 6144 MiB |
|
||||
| queue-wait (experimental) | 12 | 128 | 6144 MiB |
|
||||
| adaptive-queue (experimental) | 12 | 128 | 6144 MiB |
|
||||
| dispatch-retry (experimental) | 12 | 128 | 6144 MiB |
|
||||
| tick-dedup (experimental) | 12 | 128 | 6144 MiB |
|
||||
| culling-empty (experimental) | 12 | 128 | 6144 MiB |
|
||||
| quad-reuse (experimental) | 12 | 128 | 6144 MiB |
|
||||
| terrain-position (experimental) | 12 | 128 | 6144 MiB |
|
||||
| culling-rays (experimental) | 12 | 128 | 6144 MiB |
|
||||
| foreground-first (combined experiment) | 12 | 128 | 6144 MiB |
|
||||
| foreground-vulkan (combined experiment) | 12 | 128 | 6144 MiB |
|
||||
| low-memory | 8 | none | 3072 MiB |
|
||||
| far-distance | 12 | 256 | 8192 MiB, with sufficient physical RAM |
|
||||
| cinematic | 12 | 128 | 6144 MiB |
|
||||
| vulkan | 12 | 128 | 6144 MiB |
|
||||
|
||||
Balanced combines [Sodium](https://modrinth.com/mod/sodium), [Lithium](https://modrinth.com/mod/lithium), [FerriteCore](https://modrinth.com/mod/ferrite-core), [ImmediatelyFast](https://modrinth.com/mod/immediatelyfast), [EntityCulling](https://modrinth.com/mod/entityculling), and [Distant Horizons](https://modrinth.com/mod/distanthorizons). Cinematic adds [Iris](https://modrinth.com/mod/iris) and [Complementary Reimagined](https://modrinth.com/shader/complementary-reimagined), initially disabled. Vulkan independently experiments with the game's own backend and fallback, without Iris.
|
||||
|
||||
Distant LOD is simplified terrain. Nearby blocks retain full detail. Initial generation costs CPU/disk/memory and needs warm-up. DH adjusts clouds, chunk fade and transparency to blend its renderer; assess appearance as well as speed. Shaders cost GPU time and have [Mac-specific limits](https://shaders.properties/current/reference/miscellaneous/macos/). Universal CPU/GPU support and exact vanilla equivalence remain validation goals. Simulation distance stays 12 in every profile; normal 20 TPS rules are retained.
|
||||
|
||||
For the first comparison at the same view distance, use `baseline` versus
|
||||
`core-performance`: both select 12 full-detail chunks and no distant LOD or shaders.
|
||||
The latter adds only the pinned core performance mods and leaves every original
|
||||
controller disabled. Then test balanced separately for its additional distant
|
||||
terrain. Matching captured settings does not prove pixel-identical rendering.
|
||||
[Core comparison protocol and selected observations](docs/core-performance.md)
|
||||
include three repeated matched-view software-rendered pairs with 14–21% higher
|
||||
FPS in this workload; M2 performance remains unmeasured.
|
||||
|
||||
[Heap budget experiment](docs/heap-budget.md): three pairs with 3 GiB versus
|
||||
1.5 GiB maximum heap show variable RAM savings and GC/frame-time tradeoffs;
|
||||
playable defaults remain unchanged.
|
||||
|
||||
[Matched graphics API comparison](docs/graphics-api-comparison.md): Vulkan adds
|
||||
about 1.5% average FPS but about 12% CPU in three Linux software-rendered pairs;
|
||||
backend defaults remain unchanged and physical Mac performance is unmeasured.
|
||||
|
||||
The optional `queue-wait` pack yields during pending distant-terrain debounce retries; `adaptive-queue` combines it with the existing controllers. [Queue experiment and measurement limits](docs/debounce-queue.md).
|
||||
|
||||
Version 0.16 adds a separate [terrain position arithmetic experiment](docs/terrain-position.md)
|
||||
for the sampled full-data lookup. It retains the pinned library’s unusual
|
||||
negative-coordinate rounding and invalid-level errors. Balanced keeps it off;
|
||||
whole-game and Mac performance still require measurement.
|
||||
|
||||
Version 0.15 adds an isolated [culling ray scratch experiment](docs/culling-rays.md)
|
||||
that reuses two numeric vectors within each culling instance while retaining
|
||||
upstream arithmetic and decisions. Balanced keeps it off; hardware gains remain
|
||||
unmeasured.
|
||||
|
||||
Version 0.14 adds an isolated [empty culling whitelist experiment](docs/culling-empty.md)
|
||||
that avoids allocating iterators while there are no dynamic handlers. Live
|
||||
registration and nonempty callbacks retain upstream behavior. Balanced keeps it
|
||||
off; whole-game gains still need hardware comparisons. DH profiles also request
|
||||
a scoped [interruptible blending-read wait](docs/terrain-read-wait.md) to let
|
||||
background workers leave a pending metadata read during shutdown.
|
||||
|
||||
Version 0.13 adds an isolated [tick membership experiment](docs/tick-membership.md)
|
||||
that reuses compact storage for DH's private per-tick membership checks. The
|
||||
combined foreground profiles include it too; balanced keeps it off. The applied
|
||||
holder test verifies action semantics and removes repeated entry allocations;
|
||||
whole-game FPS and RAM gains still need hardware measurements.
|
||||
|
||||
Version 0.12 captures effective distant-terrain quality, radius, worker budgets,
|
||||
Iris state and field of view. Start/end snapshots flag changed visual settings;
|
||||
[measurement details](docs/terrain-measurements.md) explain their limits.
|
||||
|
||||
Version 0.11 adds combined foreground-first OpenGL/Vulkan profiles with a 120 FPS
|
||||
adaptive goal, plus explicit collector experiments and GC measurement guidance.
|
||||
See [combined controls](docs/foreground-first.md), [Vulkan on your Mac](docs/vulkan.md)
|
||||
and [collector comparisons](docs/collectors.md). The frame goal is not a rendering cap.
|
||||
|
||||
Version 0.10 adds an isolated [rejected-dispatch retry experiment](docs/dispatch-retry.md).
|
||||
It bounds retry passes when a DH worker rejects queued work, preserving original
|
||||
requeue handling and allowing other executors to progress. Balanced keeps it off.
|
||||
|
||||
Version 0.9 also makes the queue's idle wait wakeable for incoming work, preserving
|
||||
its debounce rules and bounded cache-maintenance cadence. It remains part of the
|
||||
optional queue profiles, with separate wake-latency measurements.
|
||||
|
||||
Version 0.8 fixes a fresh-instance graphics preset that could override the selected
|
||||
render distance. It also records actual GC/header settings and supports an optional
|
||||
[compact object headers experiment](docs/compact-headers.md) for Java 25; packs
|
||||
do not enable that JVM flag automatically.
|
||||
|
||||
## Measure on your hardware
|
||||
|
||||
The optional [adaptive terrain experiment](docs/adaptive-terrain.md) throttles distant
|
||||
terrain background work when frames slow down or heap pressure rises, keeping the
|
||||
balanced profile's view distances and simulation settings. It remains opt-in until
|
||||
real hardware demonstrates a benefit.
|
||||
|
||||
The additional [precise worker pacing experiment](docs/worker-pacing.md) makes short
|
||||
terrain tasks respect their duty-cycle budget and avoids boxed worker timestamps.
|
||||
It changes generation speed and CPU use, so it stays separate from balanced.
|
||||
|
||||
Press **F8** during gameplay to start a 120-second recording, or again to stop early. Rebind in Controls if needed. This also works with restricted chat accounts. Alternatively: `/horizon bench <label> 120`, `/horizon stop`, `/horizon status`.
|
||||
|
||||
Use separate identical world copies and the same camera route, resolution, render/simulation distance, heap, VSync and FPS limit. Warm up, then alternate at least three baseline/optimized runs. Test fresh chunk exploration separately. For everyday play cap FPS or enable VSync to reduce power usage.
|
||||
|
||||
The instance's `horizon-benchmarks/` folder receives JSON/CSV frame and integrated-server tick timings: average FPS, slowest-1%-average FPS, p95/p99 durations, stalls, JVM heap/GC, sampled process RSS when available, GPU/backend/driver and render settings. Frames include presentation/limiting waits and exclude menus/pauses/unfocused time. Tick `meanRate` is execution capacity, **not TPS**; observed tick counts are separate. Version 0.20 [captures sampled tick-manager state](docs/tick-state.md), including restored freeze/step/sprint/rate changes; this does not measure completed world work. Resident process memory is sampled on a shared background thread only during recordings; it includes native resident pages, while heap measures JVM objects. Neither is a complete measurement of unified GPU memory. [Memory measurement details](docs/process-memory.md).
|
||||
|
||||
```sh
|
||||
python3 tools/compare_benchmarks.py baseline-frames.json optimized-frames.json --strict
|
||||
```
|
||||
|
||||
Open `Compare-Benchmarks.html` from the starter ZIP or [the source file](tools/Compare-Benchmarks.html) in your browser to compare without Python. Select each JSON and optionally its matching CSV. It exports summary JSON, flags settings and duration differences, and charts frames by recorded active time or ticks by sample number. It is self-contained and makes no network requests.
|
||||
|
||||
Version 0.18 adds an isolated [terrain quad reuse experiment](docs/quad-reuse.md).
|
||||
It reuses a temporary quad discarded by successful premerge when the existing
|
||||
pool would otherwise allocate. Generated geometry and thread ownership checks
|
||||
pass; allocation results are not whole-game RAM or FPS evidence. It remains off
|
||||
in combined profiles.
|
||||
|
||||
Version 0.17 also records loaded mod versions and the Java vendor, VM and runtime
|
||||
build in client and server reports. Both comparison tools flag software changes
|
||||
as explicit experiment variables; older reports remain usable with an unknown
|
||||
software warning. The viewer can expand the complete loaded mod list.
|
||||
[Live software identity check](benchmarks/software-identity-2026-10-04/live-observations.json)
|
||||
records the metadata and file-count validation; its short capture is not a
|
||||
performance comparison.
|
||||
|
||||
|
||||
The comparison flags captured setting differences, but cannot verify route, world, shader state or cache warm-up. See [validation evidence](docs/playable-validation.md). Software-renderer test FPS is not evidence of a Mac/GPU speedup.
|
||||
|
||||
For CPU/allocation investigation, [capture and stream a private JFR summary](docs/profiling.md).
|
||||
It distinguishes directly observed allocation counters from sampled hot methods;
|
||||
profiling runs remain separate from normal timing comparisons.
|
||||
|
||||
## Build and run
|
||||
|
||||
Requires Python 3.10+ and JDK 25. No Gradle, Rust or native compilation is required for playable packs.
|
||||
|
||||
```sh
|
||||
python3 tools/build_mod.py
|
||||
python3 tools/build_release.py
|
||||
```
|
||||
|
||||
Gitignored `dist/` contains twenty packs, our original instrumentation JAR, client/server starter ZIPs and SHA256SUMS. [mods.lock.json](packs/mods.lock.json) pins mod versions, exact dependency closure, SHA-1/SHA-512 and source/license; [fabric.lock.json](packs/fabric.lock.json) pins loader/library SHA-256. Packs use the [Modrinth format](https://support.modrinth.com/en/articles/8802351-modrinth-modpack-format-mrpack). They embed only original project code; third-party mods, game and assets download from their publishers.
|
||||
|
||||
The server starter uses Lithium/FerriteCore and `/horizonserver bench <label> <seconds>`. [Server instructions](docs/server-quickstart.txt) cover setup and a baseline. Files are prepared before you accept Minecraft's EULA locally. A 50-active-player workload remains to be measured.
|
||||
|
||||
Local smoke testing uses the game's built-in limited demo; normal play uses Prism's licensed account authentication:
|
||||
|
||||
```sh
|
||||
python3 tools/build_pack.py --profile m2-balanced --instance .local/runtime/m2-balanced
|
||||
vscreen run python3 tools/runtime.py demo --instance .local/runtime/m2-balanced
|
||||
```
|
||||
|
||||
The standalone demo launcher applies the pinned official manifest's conditional
|
||||
JVM flags, including macOS `-XstartOnFirstThread` and the Windows heap-dump-path
|
||||
option. Prism applies its own official manifest. Server JVM policy is separate;
|
||||
this launcher correction is not a measured graphics performance improvement.
|
||||
|
||||
## Local game inspection
|
||||
|
||||
Game JARs, decompiled Java, libraries, inventories, worlds and logs live **inside this checkout** under gitignored **`.local/`**. No game code is in Git history or release downloads. Fresh clones regenerate the inspection workspace from official downloads; Microsoft credentials are not needed for this step.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/ludovic111/horizon.git
|
||||
cd horizon
|
||||
git config core.hooksPath .githooks
|
||||
python3 tools/lab.py prepare
|
||||
python3 tools/lab.py decompile
|
||||
python3 tools/lab.py status
|
||||
```
|
||||
|
||||
`research-lock.json` pins the official manifest and Vineflower. The inner server JAR is extracted and checked; client/server libraries provide decompiler context. Output: `.local/minecraft/26.3/sources/{client,server}/` and coverage/inventory reports. Current inventories cover 11,383 client classes and 7,762 server classes, producing 7,301/5,037 Java files. See [decompilation status](docs/decompilation-status.md).
|
||||
|
||||
Class-file SourceFile metadata covers inner classes, which often share a source file. Coverage does not prove semantic equivalence or recompilability; original bytecode remains the reference. Completed source directories are not overwritten automatically. Older obfuscated releases require a separate remapping stage.
|
||||
|
||||
## Original Rust research
|
||||
|
||||
The dependency-free `horizon-core` crate starts the Rust simulation foundation:
|
||||
integer block/chunk/section positions, legacy and xoroshiro seeded random streams and positional factories,
|
||||
padded palette-index storage, scheduled block/fluid tick queues, and double-precision
|
||||
bounding-box and voxel-grid collision geometry. Noise samplers, octave stacks and
|
||||
bulk density kernels provide the next world-generation foundation. Compiled
|
||||
density samplers add gradients, shifted and blended terrain noise, distance
|
||||
metrics and arithmetic evaluation.
|
||||
Differential runners compare selected
|
||||
operations with the checksum-pinned vanilla client and server bytecode.
|
||||
[Implemented scope, validation, and remaining rewrite work](docs/rust-parity.md).
|
||||
|
||||
```sh
|
||||
python3 tools/test_rust_parity.py --prepare
|
||||
python3 tools/test_world_parity.py
|
||||
python3 tools/test_tick_parity.py
|
||||
python3 tools/test_geometry_parity.py
|
||||
python3 tools/test_collision_parity.py
|
||||
python3 tools/test_noise_parity.py
|
||||
python3 tools/test_density_parity.py
|
||||
```
|
||||
|
||||
The core corpus checks 1,634,520 output lines per reference JAR, including
|
||||
signed boundaries, RNG rejection/state consumption and raw storage words.
|
||||
Passing it does not establish full gameplay parity or an FPS improvement.
|
||||
The separate [noise suite](docs/noise-generation.md) checks 26.3 Perlin/simplex,
|
||||
derivatives, density-volume accumulation, stack composition, normal-noise
|
||||
normalization and modern/legacy initialization against both reference JARs.
|
||||
The [density suite](docs/density-functions.md) checks compiled scalar and bulk
|
||||
evaluation, including nested samplers, their different arithmetic paths, and
|
||||
selected interval operations used for graph range analysis.
|
||||
|
||||
`horizon-world` adds NBT, four region compression codecs, `.mca`/`.mcc`
|
||||
reading and export, saved palettes, a version-checked block-state registry,
|
||||
and packed resident block sections. The world-data suite checks Rust output
|
||||
with the actual vanilla NBT, region and block-state decoders on both JARs.
|
||||
It covers all 35,723 exported state IDs and a 100,000-edit section trace.
|
||||
[World-data commands and validation limits](docs/world-data.md).
|
||||
|
||||
Scheduled ticks now support vanilla ordering, duplicate suppression, save/reload,
|
||||
chunk eligibility and callback mutations. The tick suite compares 97,776 output
|
||||
lines per reference JAR and checks saved block/fluid lists through vanilla codecs
|
||||
and region files. [Scheduler behavior and remaining integration](docs/scheduled-ticks.md).
|
||||
|
||||
Voxel shapes preserve vanilla collision tolerances, greedy box ordering, ray faces,
|
||||
inside hits, and cube-versus-array cell lookup. A cached collision registry connects
|
||||
imported shapes to resident block sections while checking exact state identities.
|
||||
Movement helpers resolve supplied colliders and step-up candidates, including
|
||||
landing adjustment and the second collider query. Movement-path block visits
|
||||
preserve vanilla ordering, step indices and packed-position deduplication.
|
||||
Uncached states require block behavior; the entity-context overload also needs
|
||||
separate implementation. [Geometry and collision scope](docs/collision-geometry.md).
|
||||
|
||||
```sh
|
||||
cargo test --workspace
|
||||
cargo run --release --bin voxel-bench -- 100 > .local/voxel-benchmark.csv
|
||||
```
|
||||
|
||||
The dependency-free occupancy experiment compares scalar and bitset exposed-face counting for synthetic 16³ sections. It has no real mesh, material/AO/light work, neighboring-section context, JNI bridge or game integration. Speedups are kernel-only, not Minecraft FPS. [Research plan](docs/optimization-plan.md) describes profiling, improved Java baselines, native integration and behavior checks before expanding scope.
|
||||
|
||||
Public branding and new mod downloads use **Horizon**. The existing Fabric mod
|
||||
ID and `dev.horizonlab` namespace remain stable for installed instances and
|
||||
measurement compatibility. The installer backs up both old `horizon-lab-*.jar`
|
||||
and new `horizon-*.jar` versions before installing an update.
|
||||
|
||||
## Validation and ownership
|
||||
|
||||
```sh
|
||||
python3 -m unittest discover -s tests -v
|
||||
python3 tools/build_mod.py --test-only
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
python3 tools/check_public_tree.py
|
||||
python3 tools/check_public_tree.py --history
|
||||
```
|
||||
|
||||
CI checks offline tools/Rust and compiles the original mod/builds packs on Linux and Apple Silicon macOS. Game dependencies download to ephemeral `.local/`; CI uploads only our original JAR and packs. Compilation is not Mac GPU gameplay testing. Publication checks allow Java only under our original `dev/horizonlab` namespace; review diffs as well.
|
||||
CI runs these checks on GitHub's Linux runners. The vanilla comparisons need the game, which Horizon never downloads, so they run only when started by hand on a self-hosted runner holding the maintainer's own copy. Never commit game files, decompiled source or prepared resources: `tools/check_public_tree.py` rejects them, and tracked Java is allowed only under the project's own `dev/horizonlab` namespace.
|
||||
|
||||
[MIT](LICENSE) covers only our original tracked work. Dependencies retain their licenses. Mojang [removed obfuscation](https://www.minecraft.net/en-us/article/removing-obfuscation-in-java-edition) without changing [Minecraft's EULA](https://www.minecraft.net/en-us/eula). Decompiled game source remains local; published code implements independent tooling and instrumentation.
|
||||
## Licence
|
||||
|
||||
Integrated-server reports record the shared graphics backend at recording start; see [the context and comparison limits](docs/server-graphics-context.md).
|
||||
[MIT](LICENSE), for the project's original work only. Dependencies keep their own licences. Minecraft is a trademark of Mojang Synergies AB; Minecraft code and assets belong to Mojang and Microsoft and are covered by the [Minecraft EULA](https://www.minecraft.net/en-us/eula). Decompiled game source and prepared resources stay on your machine and are never published.
|
||||
|
||||
## Author
|
||||
|
||||
Made by [Ludovic Marie](https://lu4ovic.com) ([@ludovic111](https://github.com/ludovic111)).
|
||||
|
||||
@@ -80,10 +80,13 @@ fn main() -> horizon_client::Result<()> {
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
// The inventory menu never reads banner patterns.
|
||||
let banners = horizon_client::banner::Banners::default();
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for line in input.lines() {
|
||||
|
||||
@@ -8,7 +8,7 @@ use horizon_client::mobs::{
|
||||
anim::{self, Poses, State},
|
||||
aquatic, body_anim as b_anim, equine, guardian,
|
||||
keyframes::AnimationState,
|
||||
shulker, species, tame,
|
||||
shulker, sniffer, species, tame,
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
@@ -173,6 +173,56 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
|
||||
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
|
||||
}
|
||||
}
|
||||
Species::Breeze => {
|
||||
// breeze::anim's state slots.
|
||||
for (i, k) in ["idle", "shoot", "slide", "slideBack", "inhale", "longJump"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
|
||||
}
|
||||
}
|
||||
Species::Sniffer => {
|
||||
if flag("isSearching") {
|
||||
mob.extra.variant = sniffer::SEARCHING;
|
||||
}
|
||||
// Sniffer's animation states, in `sniffer::anim`'s order.
|
||||
for (i, k) in [
|
||||
"feelingHappyAnimationState",
|
||||
"scentingAnimationState",
|
||||
"sniffingAnimationState",
|
||||
"diggingAnimationState",
|
||||
"risingAnimationState",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
|
||||
}
|
||||
}
|
||||
Species::HappyGhast => {
|
||||
mob.extra.head = case["bodyItem"].as_str().map(Into::into);
|
||||
if flag("isRidden") {
|
||||
mob.rider = Some(Default::default());
|
||||
}
|
||||
}
|
||||
Species::Warden => {
|
||||
use horizon_client::mobs::warden;
|
||||
mob.anim.v[warden::TENDRIL] = num("tendrilAnimation") * 10.0;
|
||||
mob.anim.vo[warden::TENDRIL] = num("tendrilAnimation") * 10.0;
|
||||
mob.anim.v[warden::HEART] = num("heartAnimation") * 10.0;
|
||||
mob.anim.vo[warden::HEART] = num("heartAnimation") * 10.0;
|
||||
for (i, k) in [
|
||||
(warden::ROAR, "roarAnimationState"),
|
||||
(warden::SNIFF, "sniffAnimationState"),
|
||||
(warden::EMERGE, "emergeAnimationState"),
|
||||
(warden::DIGGING, "diggingAnimationState"),
|
||||
(warden::ATTACK, "attackAnimationState"),
|
||||
(warden::SONIC_BOOM, "sonicBoomAnimationState"),
|
||||
] {
|
||||
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
|
||||
}
|
||||
}
|
||||
Species::Witch if flag("isHoldingItem") => {
|
||||
mob.extra.main_hand = Some("minecraft:potion".into());
|
||||
}
|
||||
@@ -215,6 +265,13 @@ fn main() -> horizon_client::Result<()> {
|
||||
base = base.replace(cut, "");
|
||||
}
|
||||
let base = base.replace("undead_horse#", "zombie_horse#");
|
||||
// The breeze's wind and eyes and the creaking's eyes are layers of
|
||||
// the species' own model class; LlamaDecorLayer's model animates like
|
||||
// the llama.
|
||||
let base = base
|
||||
.replace("#wind", "#main")
|
||||
.replace("#eyes", "#main")
|
||||
.replace("#decor", "#main");
|
||||
let base = base.trim_start_matches("cold_").trim_start_matches("warm_");
|
||||
let Some(def) = species::ALL.iter().find(|d| {
|
||||
d.model == layer
|
||||
@@ -222,6 +279,11 @@ fn main() -> horizon_client::Result<()> {
|
||||
|| d.model == base
|
||||
|| d.model.trim_end_matches("#main") == base.trim_end_matches("#main")
|
||||
|| norm(d.model) == base
|
||||
// The warden's emissive layers are its model over other parts.
|
||||
|| (["#tendrils", "#heart", "#bioluminescent", "#pulsating_spots"]
|
||||
.iter()
|
||||
.any(|s| layer.ends_with(s))
|
||||
&& d.model == format!("{}#main", layer.split('#').next().unwrap_or_default()))
|
||||
}) else {
|
||||
out.push_str(&format!("{}\n", json!({"skip": "no species"})));
|
||||
continue;
|
||||
@@ -370,6 +432,22 @@ fn main() -> horizon_client::Result<()> {
|
||||
},
|
||||
&animations,
|
||||
),
|
||||
Species::CopperGolem => {
|
||||
// CopperGolemRenderState's animation states, in the golem's slots.
|
||||
for (slot, key) in [
|
||||
"idleAnimationState",
|
||||
"interactionGetItem",
|
||||
"interactionGetNoItem",
|
||||
"interactionDropItem",
|
||||
"interactionDropNoItem",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
mob.anim.states[slot] = started(key);
|
||||
}
|
||||
horizon_client::mobs::copper_golem::anim(&mob, s, p, &animations);
|
||||
}
|
||||
Species::Rabbit => b_anim::rabbit(
|
||||
p,
|
||||
s,
|
||||
|
||||
@@ -35,10 +35,12 @@ fn main() -> horizon_client::Result<()> {
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
let banners = horizon_client::banner::Banners::load(root);
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for line in input.lines() {
|
||||
@@ -50,6 +52,7 @@ fn main() -> horizon_client::Result<()> {
|
||||
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
|
||||
}
|
||||
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
|
||||
menu.settle(&env);
|
||||
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
|
||||
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
|
||||
}
|
||||
@@ -58,6 +61,23 @@ fn main() -> horizon_client::Result<()> {
|
||||
for op in case["ops"].as_array().ok_or("ops")? {
|
||||
let slot = op[0].as_i64().unwrap_or(0) as i32;
|
||||
let button = op[1].as_i64().unwrap_or(0) as i32;
|
||||
match op[2].as_str().unwrap_or_default() {
|
||||
// ServerboundContainerButtonClickPacket: clickMenuButton.
|
||||
"BUTTON" => {
|
||||
menu.button(&env, slot);
|
||||
out += &format!("{}\n", state(&menu));
|
||||
continue;
|
||||
}
|
||||
// ServerboundContainerSlotStateChangedPacket.
|
||||
"SLOT_STATE" => {
|
||||
if (0..9).contains(&slot) {
|
||||
menu.set_slot_state(slot as usize, button == 1);
|
||||
}
|
||||
out += &format!("{}\n", state(&menu));
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?;
|
||||
match menu.click(&env, slot, button, kind) {
|
||||
Ok(()) => out += &format!("{}\n", state(&menu)),
|
||||
|
||||
@@ -9,8 +9,13 @@ use horizon_client::{
|
||||
blocks::BlockFacts,
|
||||
chunk::{Chunk, HEIGHT, MIN_Y},
|
||||
collisions,
|
||||
containers::{BlockEntity, CreakingHeart},
|
||||
items::Items,
|
||||
light::{LightTables, light_chunk},
|
||||
mobs::{
|
||||
Damage, MobType, creaking,
|
||||
creaking_heart::{self, HeartEvent, HeartHost},
|
||||
},
|
||||
mobs::{
|
||||
Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who,
|
||||
control::Operation, spawning::LocalDifficulty,
|
||||
@@ -43,6 +48,15 @@ struct Scenario {
|
||||
blocks: Vec<Vec<String>>,
|
||||
player: Option<[f64; 3]>,
|
||||
creative: bool,
|
||||
/// The tick from which the player faces another yaw.
|
||||
turn: Option<(i32, f32)>,
|
||||
/// Creaking hearts placed when the scenario starts.
|
||||
hearts: Vec<Vec<String>>,
|
||||
/// `ServerLevel.isSpawningMonsters`.
|
||||
spawning: bool,
|
||||
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
|
||||
hurts: Vec<(i32, usize)>,
|
||||
hand: Option<String>,
|
||||
mobs: Vec<MobSpec>,
|
||||
}
|
||||
|
||||
@@ -67,19 +81,33 @@ fn parse(text: &str) -> Vec<Scenario> {
|
||||
"rain" => s.rain = true,
|
||||
"thunder" => s.thunder = true,
|
||||
"levelseed" => {}
|
||||
"spawning" => s.spawning = true,
|
||||
_ => panic!("unknown scenario option {kv}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
"origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()],
|
||||
"fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()),
|
||||
"heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()),
|
||||
"hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())),
|
||||
"player" => {
|
||||
s.player = Some([
|
||||
f[1].parse().unwrap(),
|
||||
f[2].parse().unwrap(),
|
||||
f[3].parse().unwrap(),
|
||||
]);
|
||||
s.creative = f.get(4) == Some(&"creative");
|
||||
for opt in &f[4..] {
|
||||
if *opt == "creative" {
|
||||
s.creative = true;
|
||||
} else if let Some(t) = opt.strip_prefix("turn=") {
|
||||
let (tick, yaw) = t.split_once(',').unwrap();
|
||||
s.turn = Some((tick.parse().unwrap(), yaw.parse().unwrap()));
|
||||
} else if let Some(item) = opt.strip_prefix("hand=") {
|
||||
s.hand = Some(item.to_owned());
|
||||
} else {
|
||||
panic!("unknown player option {opt}");
|
||||
}
|
||||
}
|
||||
}
|
||||
"mob" => s.mobs.push(MobSpec {
|
||||
kind: f[1].to_owned(),
|
||||
@@ -237,9 +265,99 @@ fn seen(m: &Mob) -> Seen {
|
||||
.flatten(),
|
||||
profession: m.extra.variant2,
|
||||
xp: horizon_client::mobs::villager::xp(m),
|
||||
stats: [
|
||||
f64::from(m.attrs.max_health),
|
||||
m.extra.vector[0],
|
||||
m.attrs.speed,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe's mobs as a creaking heart sees them: creakings it creates take
|
||||
/// the n-th seed from 1000, as the oracle's do.
|
||||
struct Host<'a> {
|
||||
mobs: &'a mut Vec<Mob>,
|
||||
added: Vec<Mob>,
|
||||
types: &'a MobTypes,
|
||||
created: &'a mut i64,
|
||||
spawning: bool,
|
||||
}
|
||||
impl HeartHost for Host<'_> {
|
||||
fn mob(&self, id: u32) -> Option<&Mob> {
|
||||
self.mobs
|
||||
.iter()
|
||||
.chain(self.added.iter())
|
||||
.find(|m| m.id == id)
|
||||
}
|
||||
fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> {
|
||||
self.mobs
|
||||
.iter_mut()
|
||||
.chain(self.added.iter_mut())
|
||||
.find(|m| m.id == id)
|
||||
}
|
||||
fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
|
||||
self.mob(uuid[3] as u32)
|
||||
.filter(|m| !m.removed)
|
||||
.map(|m| m.id)
|
||||
}
|
||||
fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
||||
[0, 0, 0, id as i32]
|
||||
}
|
||||
fn creaking_type(&self) -> Option<Arc<MobType>> {
|
||||
self.types
|
||||
.types
|
||||
.get("minecraft:creaking")
|
||||
.map(|t| Arc::new(t.clone()))
|
||||
}
|
||||
fn create_mob(&mut self, kind: Arc<MobType>, at: Vec3) -> Mob {
|
||||
let seed = 1000 + *self.created;
|
||||
*self.created += 1;
|
||||
let mut m = Mob::new(200_000 + seed as u32, kind, at, 0.0);
|
||||
m.random = LegacyRandom::new(seed);
|
||||
horizon_client::mobs::monster_brain::init(&mut m, seed);
|
||||
m
|
||||
}
|
||||
fn add_mob(&mut self, m: Mob) {
|
||||
self.added.push(m);
|
||||
}
|
||||
fn spawning_monsters(&self) -> bool {
|
||||
self.spawning
|
||||
}
|
||||
}
|
||||
/// The heart's state, block entity and the level random, as the oracle
|
||||
/// prints them.
|
||||
fn print_heart(
|
||||
out: &mut String,
|
||||
t: i32,
|
||||
registry: &BlockRegistry,
|
||||
world: &World,
|
||||
at: [i32; 3],
|
||||
heart: &CreakingHeart,
|
||||
lr: &LegacyRandom,
|
||||
) {
|
||||
let state = registry
|
||||
.state(world.block(at[0], at[1], at[2]))
|
||||
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
|
||||
.unwrap_or_default();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{t} heart {},{},{}\t{state}\t{} {} {} {} {}\tlrng {:x}",
|
||||
at[0],
|
||||
at[1],
|
||||
at[2],
|
||||
heart.ticker,
|
||||
heart.emitter,
|
||||
heart.output_signal,
|
||||
heart.ticks_existed,
|
||||
if heart.creaking.is_some() {
|
||||
"linked"
|
||||
} else {
|
||||
"none"
|
||||
},
|
||||
lr.state()
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether an event hurts the scenario's player (survival, normal difficulty,
|
||||
/// no armour, made hurtable again every tick by the oracle).
|
||||
fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
|
||||
@@ -355,7 +473,10 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
|
||||
u8::from(m.ai.jumping)
|
||||
);
|
||||
let _ = write!(out, "\trng {:x}", m.random.state());
|
||||
if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) {
|
||||
let brain = horizon_client::mobs::villager_brain::describe(m)
|
||||
.or_else(|| horizon_client::mobs::monster_brain::describe(m))
|
||||
.or_else(|| horizon_client::mobs::animal_brain::describe(m));
|
||||
if let Some((acts, mem)) = brain {
|
||||
let _ = write!(out, "\tact {acts}\tmem {mem}");
|
||||
}
|
||||
out.push('\n');
|
||||
@@ -425,6 +546,17 @@ fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut hearts: Vec<([i32; 3], CreakingHeart)> = Vec::new();
|
||||
for h in &s.hearts {
|
||||
let at = [
|
||||
h[1].parse::<i32>().unwrap(),
|
||||
h[2].parse::<i32>().unwrap(),
|
||||
h[3].parse::<i32>().unwrap(),
|
||||
];
|
||||
world.set(at[0], at[1], at[2], state(registry, &h[4]))?;
|
||||
hearts.push((at, CreakingHeart::default()));
|
||||
}
|
||||
let mut created = 0_i64;
|
||||
let keys: Vec<(i32, i32)> = world.chunks.keys().copied().collect();
|
||||
let lit: Vec<((i32, i32), Chunk)> = keys
|
||||
.iter()
|
||||
@@ -467,10 +599,24 @@ fn main() -> horizon_client::Result<()> {
|
||||
match flag.as_str() {
|
||||
"persistent" => m.persistent = true,
|
||||
"noai" => m.no_ai = true,
|
||||
"inlove" => m.extra.in_love = 600,
|
||||
"tame" => m.extra.tame = true,
|
||||
x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(),
|
||||
x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(),
|
||||
"leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player),
|
||||
x if x.starts_with("leashto=") => {
|
||||
let n: u32 = x[8..].parse().unwrap();
|
||||
m.extra.leash = Some(horizon_client::mobs::leash::Holder::Mob(100_000 + n));
|
||||
}
|
||||
other => panic!("unknown mob flag {other}"),
|
||||
}
|
||||
}
|
||||
m.random = LegacyRandom::new(spec.seed);
|
||||
if horizon_client::mobs::monster_brain::has_brain(m.species()) {
|
||||
// The oracle delays the sensors again with the seeded random
|
||||
// and seeds RunOne's shuffles with the mob's seed.
|
||||
horizon_client::mobs::monster_brain::init(&mut m, spec.seed);
|
||||
}
|
||||
if m.species() == Species::Villager {
|
||||
// The oracle seeds the random after the brain is built, then
|
||||
// delays the sensors again and seeds the gates' shuffles.
|
||||
@@ -481,9 +627,13 @@ fn main() -> horizon_client::Result<()> {
|
||||
spec.seed,
|
||||
);
|
||||
}
|
||||
// The same for the sniffer's and the happy ghast's brains.
|
||||
if horizon_client::mobs::animal_brain::kind_of(&m).is_some() {
|
||||
horizon_client::mobs::animal_brain::init(&mut m, spec.seed);
|
||||
}
|
||||
mobs.push(m);
|
||||
}
|
||||
let player = s.player.map(|p| {
|
||||
let mut player = s.player.map(|p| {
|
||||
let position = Vec3::new(p[0], p[1], p[2]);
|
||||
PlayerView {
|
||||
position,
|
||||
@@ -496,7 +646,7 @@ fn main() -> horizon_client::Result<()> {
|
||||
creative: s.creative,
|
||||
sneaking: false,
|
||||
look: [0.0, 0.0, 1.0],
|
||||
main_hand: None,
|
||||
main_hand: s.hand.as_deref().map(Into::into),
|
||||
off_hand: None,
|
||||
head: None,
|
||||
armor_cover: 0.0,
|
||||
@@ -508,46 +658,121 @@ fn main() -> horizon_client::Result<()> {
|
||||
yaw: 0.0,
|
||||
hero: false,
|
||||
uuid: [0, 0x1234, 0, 0x5678],
|
||||
allies: Default::default(),
|
||||
}
|
||||
});
|
||||
let mut scratch = LegacyRandom::new(0);
|
||||
for (i, m) in mobs.iter().enumerate() {
|
||||
print(&mut out, 0, i, m);
|
||||
}
|
||||
// The MobWorld every step sees, over a snapshot of the mobs.
|
||||
macro_rules! mob_world {
|
||||
($snapshot:expr) => {
|
||||
MobWorld {
|
||||
teams: Default::default(),
|
||||
world: &world,
|
||||
registry,
|
||||
facts: &facts,
|
||||
collision: &collision,
|
||||
data: &data,
|
||||
player: player.clone(),
|
||||
others: $snapshot,
|
||||
daylight: (s.time.rem_euclid(24000)) < 12000,
|
||||
game_time: world.game_time,
|
||||
day_time: world.day_time,
|
||||
raining: s.rain,
|
||||
thundering: s.thunder,
|
||||
nether: false,
|
||||
block_tags: &items.block_tags,
|
||||
biomes: &biomes,
|
||||
mob_griefing: true,
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
sea_level: -63,
|
||||
}
|
||||
};
|
||||
}
|
||||
for t in 1..=s.ticks {
|
||||
world.game_time += 1;
|
||||
let snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
||||
let w = MobWorld {
|
||||
world: &world,
|
||||
registry,
|
||||
facts: &facts,
|
||||
collision: &collision,
|
||||
data: &data,
|
||||
player: player.clone(),
|
||||
others: &snapshot,
|
||||
daylight: (s.time.rem_euclid(24000)) < 12000,
|
||||
game_time: world.game_time,
|
||||
day_time: world.day_time,
|
||||
raining: s.rain,
|
||||
thundering: s.thunder,
|
||||
nether: false,
|
||||
block_tags: &items.block_tags,
|
||||
biomes: &biomes,
|
||||
mob_griefing: true,
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
sea_level: -63,
|
||||
};
|
||||
let mut heart_events_later: Vec<HeartEvent> = Vec::new();
|
||||
// Creaking.tick reads the heart's block entity.
|
||||
for (at, h) in &hearts {
|
||||
world.block_entities.insert(
|
||||
(at[0], at[1], at[2]),
|
||||
BlockEntity::CreakingHeart(Box::new(h.clone())),
|
||||
);
|
||||
}
|
||||
if let (Some(p), Some((tick, yaw))) = (player.as_mut(), s.turn)
|
||||
&& t >= tick
|
||||
{
|
||||
// Entity.calculateViewVector(0, yaw).
|
||||
let r = -yaw * horizon_core::geometry::trig::DEG_TO_RAD;
|
||||
let (cos, sin) = (
|
||||
horizon_core::geometry::trig::cos(f64::from(r)),
|
||||
horizon_core::geometry::trig::sin(f64::from(r)),
|
||||
);
|
||||
p.look = [f64::from(sin), -0.0, f64::from(cos)];
|
||||
p.yaw = yaw;
|
||||
}
|
||||
let mut snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
||||
let w = mob_world!(&snapshot);
|
||||
let mut events = Vec::new();
|
||||
let mut heart_events = Vec::new();
|
||||
let mut added = Vec::new();
|
||||
for &(tick, i) in &s.hurts {
|
||||
if tick != t || i >= mobs.len() || mobs[i].removed {
|
||||
continue;
|
||||
}
|
||||
let at = player
|
||||
.as_ref()
|
||||
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]);
|
||||
mobs[i].damage(1.0, Damage::player(at));
|
||||
// Creaking.hurtServer: the heart's reaction, then the sway.
|
||||
if let Some((home, by_player)) = creaking::take_hurt(&mut mobs[i], &w) {
|
||||
if by_player && let Some((_, h)) = hearts.iter_mut().find(|(at, _)| *at == home)
|
||||
{
|
||||
let mut host = Host {
|
||||
mobs: &mut mobs,
|
||||
added: Vec::new(),
|
||||
types: &types,
|
||||
created: &mut created,
|
||||
spawning: s.spawning,
|
||||
};
|
||||
creaking_heart::creaking_hurt(
|
||||
h,
|
||||
home,
|
||||
&w,
|
||||
&mut scratch,
|
||||
&mut host,
|
||||
&mut heart_events,
|
||||
);
|
||||
added.append(&mut host.added);
|
||||
}
|
||||
for e in heart_events.drain(..) {
|
||||
match e {
|
||||
HeartEvent::Sound(name, _, volume, pitch) => {
|
||||
events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch))
|
||||
}
|
||||
HeartEvent::SetBlock(..) => heart_events_later.push(e),
|
||||
HeartEvent::Mob(ev) => events.push(ev),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
creaking::sway(&mut mobs[i], &mut events);
|
||||
}
|
||||
events.append(&mut mobs[i].outbox);
|
||||
}
|
||||
#[allow(unused_mut)] // filled only with the rng-trace feature
|
||||
let mut traces: Vec<String> = Vec::new();
|
||||
let mut pushes = Vec::new();
|
||||
for (i, m) in mobs.iter_mut().enumerate() {
|
||||
if m.removed {
|
||||
for i in 0..mobs.len() {
|
||||
if mobs[i].removed {
|
||||
continue;
|
||||
}
|
||||
let w = mob_world!(&snapshot);
|
||||
let m = &mut mobs[i];
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
#[cfg(feature = "rng-trace")]
|
||||
@@ -561,14 +786,53 @@ fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
}
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
let _ = i;
|
||||
if !alive {
|
||||
m.removed = true;
|
||||
}
|
||||
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
|
||||
// ServerLevel ticks entities one after another: the ones
|
||||
// after this mob see it as it is now.
|
||||
if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) {
|
||||
*e = seen(&mobs[i]);
|
||||
e.alive &= !mobs[i].removed;
|
||||
}
|
||||
}
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
let w = mob_world!(&snapshot);
|
||||
// ServerLevel.tickBlockEntities: the hearts (none ticks once uprooted).
|
||||
heart_events.append(&mut heart_events_later);
|
||||
for (at, h) in &mut hearts {
|
||||
let uprooted = registry
|
||||
.state(w.world.block(at[0], at[1], at[2]))
|
||||
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
|
||||
.is_some_and(|v| v == "uprooted");
|
||||
if uprooted {
|
||||
continue;
|
||||
}
|
||||
let mut host = Host {
|
||||
mobs: &mut mobs,
|
||||
added: Vec::new(),
|
||||
types: &types,
|
||||
created: &mut created,
|
||||
spawning: s.spawning,
|
||||
};
|
||||
creaking_heart::server_tick(h, *at, &w, &mut scratch, &mut host, &mut heart_events);
|
||||
added.append(&mut host.added);
|
||||
}
|
||||
drop(w);
|
||||
mobs.append(&mut added);
|
||||
for e in &heart_events {
|
||||
match e {
|
||||
HeartEvent::SetBlock(at, st) => world.set(at[0], at[1], at[2], *st)?,
|
||||
HeartEvent::Sound(name, _, volume, pitch) => {
|
||||
events.push(MobEvent::Sound(name, [0.0; 3], *volume, *pitch))
|
||||
}
|
||||
HeartEvent::Mob(ev) => events.push(ev.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (i, m) in mobs.iter().enumerate() {
|
||||
print(&mut out, t, i, m);
|
||||
}
|
||||
@@ -591,6 +855,9 @@ fn main() -> horizon_client::Result<()> {
|
||||
);
|
||||
}
|
||||
}
|
||||
for (at, h) in &hearts {
|
||||
print_heart(&mut out, t, registry, &world, *at, h, &scratch);
|
||||
}
|
||||
for line in traces {
|
||||
let _ = writeln!(out, "{line}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Recipe book placements for tools/test_place_recipe_parity.py: reads one
|
||||
//! JSON case per line (menu, inventory, grid, recipe, max, creative,
|
||||
//! selected) and the oracle's order of the counted items, runs
|
||||
//! `Menu::place_recipe` and prints the oracle's line.
|
||||
//!
|
||||
//! usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT
|
||||
use horizon_client::{
|
||||
crafting::Recipes,
|
||||
item_data::{canon_stack, parse_stack},
|
||||
items::Items,
|
||||
menu::{Env, Kind, Menu, place::PostPlace},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{fs, path::Path};
|
||||
|
||||
fn state(menu: &Menu) -> String {
|
||||
let slots: Vec<String> = (0..menu.slot_count())
|
||||
.map(|i| canon_stack(menu.slot(i)))
|
||||
.collect();
|
||||
let data: String = menu.data.iter().map(|d| format!(" {d}")).collect();
|
||||
let inv: Vec<String> = (0..41).map(|i| canon_stack(menu.player_item(i))).collect();
|
||||
format!(
|
||||
"{} | {} |{data} | {} | inv {}",
|
||||
slots.join(" "),
|
||||
canon_stack(menu.carried.as_ref()),
|
||||
menu.drops.join(";"),
|
||||
inv.join(" ")
|
||||
)
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT";
|
||||
let root = Path::new(args.get(1).ok_or(usage)?);
|
||||
let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?;
|
||||
let orders = fs::read_to_string(args.get(3).ok_or(usage)?)?;
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
let banners = horizon_client::banner::Banners::default();
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (line, order) in cases.lines().zip(orders.lines()) {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?;
|
||||
let mut menu = Menu::new(kind);
|
||||
menu.creative = case["creative"].as_bool().unwrap_or(false);
|
||||
menu.selected = case["selected"].as_u64().unwrap_or(0) as usize;
|
||||
for pair in case["inventory"].as_array().ok_or("inventory")? {
|
||||
menu.set_player_item(
|
||||
pair[0].as_u64().unwrap_or(0) as usize,
|
||||
parse_stack(pair[1].as_str().unwrap_or("-"))?,
|
||||
);
|
||||
}
|
||||
for pair in case["grid"].as_array().ok_or("grid")? {
|
||||
menu.set_slot(
|
||||
&env,
|
||||
pair[0].as_u64().unwrap_or(0) as usize,
|
||||
parse_stack(pair[1].as_str().unwrap_or("-"))?,
|
||||
);
|
||||
}
|
||||
menu.drops.clear();
|
||||
let order: Vec<String> = order.split_whitespace().map(str::to_owned).collect();
|
||||
let recipe = case["recipe"].as_str().unwrap_or_default();
|
||||
let impossible = recipes.placement(recipe).is_none_or(|p| p.impossible());
|
||||
let post = if impossible {
|
||||
"-"
|
||||
} else {
|
||||
match menu.place_recipe(
|
||||
&env,
|
||||
recipe,
|
||||
case["max"].as_bool().unwrap_or(false),
|
||||
menu.creative,
|
||||
Some(&order),
|
||||
) {
|
||||
PostPlace::Nothing => "NOTHING",
|
||||
PostPlace::Ghost => "PLACE_GHOST_RECIPE",
|
||||
}
|
||||
};
|
||||
out += &format!("post {post} | {}\n", state(&menu));
|
||||
}
|
||||
fs::write(args.get(4).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
//! The player's recipe book for tools/test_recipe_book_parity.py: reads one
|
||||
//! JSON case per line (a list of give / take / seen / set / save / load ops)
|
||||
//! and prints the oracle's line after each op, from
|
||||
//! `horizon_client::recipe_book::{Settings, RecipeIndex}`.
|
||||
//!
|
||||
//! usage: recipe_book_fixture RESOURCES CASES OUTPUT
|
||||
use horizon_client::recipe_book::{BookType, RecipeIndex, Settings};
|
||||
use horizon_world::nbt::Tag;
|
||||
use serde_json::Value;
|
||||
use std::{collections::BTreeSet, fs, path::Path};
|
||||
|
||||
fn fnv<'a>(ids: impl IntoIterator<Item = &'a String>) -> u64 {
|
||||
let mut sorted: Vec<&String> = ids.into_iter().collect();
|
||||
sorted.sort();
|
||||
let joined = sorted
|
||||
.iter()
|
||||
.map(|s| s.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in joined.bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
fn ids(set: &BTreeSet<String>) -> String {
|
||||
format!("{}:{:x}", set.len(), fnv(set))
|
||||
}
|
||||
/// The saved compound as the oracle prints it: keys sorted, lists hashed.
|
||||
fn compound(tag: &Tag) -> String {
|
||||
let Tag::Compound(c) = tag else {
|
||||
return String::new();
|
||||
};
|
||||
let mut keys: Vec<String> = c.keys().map(|k| k.to_string_lossy()).collect();
|
||||
keys.sort();
|
||||
let mut out = String::new();
|
||||
for k in keys {
|
||||
out.push(' ');
|
||||
out.push_str(&k);
|
||||
out.push('=');
|
||||
match tag.get(&k) {
|
||||
Some(Tag::List(list)) => {
|
||||
let v: Vec<String> = list
|
||||
.iter()
|
||||
.map(|t| match t {
|
||||
Tag::String(s) => s.to_string_lossy(),
|
||||
_ => "?".into(),
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&format!("{}:{:x}", v.len(), fnv(&v)));
|
||||
}
|
||||
Some(Tag::Byte(b)) => out.push_str(&format!("{b}b")),
|
||||
_ => out.push('?'),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: recipe_book_fixture RESOURCES CASES OUTPUT";
|
||||
let root = Path::new(args.get(1).ok_or(usage)?);
|
||||
let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?;
|
||||
let index = RecipeIndex::load(root);
|
||||
let mut out = String::new();
|
||||
for line in cases.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let mut book = Settings::default();
|
||||
let mut saved: Option<Tag> = None;
|
||||
for op in case["ops"].as_array().ok_or("ops")? {
|
||||
let kind = op["op"].as_str().unwrap_or_default();
|
||||
let list = || -> Vec<String> {
|
||||
op["ids"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|id| index.contains(id))
|
||||
.collect()
|
||||
};
|
||||
let mut count = 0;
|
||||
let mut extra = String::new();
|
||||
match kind {
|
||||
"give" => count = book.add_recipes(&index, &list()).0,
|
||||
"take" => count = book.remove_recipes(&index, &list()),
|
||||
"seen" => book.remove_highlight(op["id"].as_str().unwrap_or_default()),
|
||||
"set" => {
|
||||
let i = match op["type"].as_str().unwrap_or_default() {
|
||||
"CRAFTING" => BookType::Crafting,
|
||||
"FURNACE" => BookType::Furnace,
|
||||
"BLAST_FURNACE" => BookType::BlastFurnace,
|
||||
_ => BookType::Smoker,
|
||||
}
|
||||
.index();
|
||||
book.open[i] = op["open"].as_bool().unwrap_or(false);
|
||||
book.filtering[i] = op["filtering"].as_bool().unwrap_or(false);
|
||||
}
|
||||
"save" => {
|
||||
let tag = book.write();
|
||||
extra = compound(&tag);
|
||||
saved = Some(tag);
|
||||
}
|
||||
"load" => {
|
||||
let mut tag = saved
|
||||
.clone()
|
||||
.unwrap_or_else(|| Tag::Compound(Default::default()));
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
for name in ["recipes", "toBeDisplayed"] {
|
||||
if let Some(Tag::List(l)) = c.get_mut(&name.into()) {
|
||||
l.push(Tag::String("minecraft:no_such_recipe".into()));
|
||||
l.push(Tag::String("stick".into()));
|
||||
}
|
||||
}
|
||||
if let Some(drop) = op["drop"].as_str() {
|
||||
c.remove(&drop.into());
|
||||
}
|
||||
}
|
||||
book = Settings::read_valid(Some(&tag), &|id| index.contains(id));
|
||||
}
|
||||
other => return Err(format!("op {other}").into()),
|
||||
}
|
||||
let settings: String = BookType::ALL
|
||||
.iter()
|
||||
.map(|b| {
|
||||
format!(
|
||||
"{}{}",
|
||||
u8::from(book.open[b.index()]),
|
||||
u8::from(book.filtering[b.index()])
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out += &format!(
|
||||
"{kind} {count} known={} highlight={} settings={settings}{extra}\n",
|
||||
ids(&book.recipes),
|
||||
ids(&book.to_be_displayed)
|
||||
);
|
||||
}
|
||||
out += "end\n";
|
||||
}
|
||||
fs::write(args.get(3).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! What the recipe book lists, for tools/test_recipe_book_view_parity.py:
|
||||
//! reads one JSON case per line (the history of displays the client was
|
||||
//! sent, the book type and grid, the inventory and menu slots, the filter)
|
||||
//! and prints every tab's visibility, page count and buttons from
|
||||
//! `horizon_client::recipe_book::ClientBook`.
|
||||
//!
|
||||
//! usage: recipe_book_view_fixture RESOURCES CASES OUTPUT
|
||||
use horizon_client::{
|
||||
crafting::Recipes,
|
||||
item_data::parse_stack,
|
||||
items::Items,
|
||||
menu::place::Stacked,
|
||||
recipe_book::{Book, BookType, ClientBook, Display, RecipeIndex, Tab},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{fmt::Write as _, fs, path::Path};
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: recipe_book_view_fixture RESOURCES CASES OUTPUT";
|
||||
let root = Path::new(args.get(1).ok_or(usage)?);
|
||||
let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?;
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let index = RecipeIndex::load(root);
|
||||
let mut book = Book::build(&recipes, &items);
|
||||
book.set_display_ids(&index);
|
||||
let max = |s: &horizon_client::items::ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack);
|
||||
let mut out = String::new();
|
||||
for line in cases.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let mut client = ClientBook::default();
|
||||
for batch in case["history"].as_array().ok_or("history")? {
|
||||
let op = batch["op"].as_str().unwrap_or_default();
|
||||
if op == "replace" {
|
||||
client.clear();
|
||||
}
|
||||
for id in batch["ids"].as_array().into_iter().flatten() {
|
||||
for d in index.display_ids(id.as_str().unwrap_or_default()) {
|
||||
if op == "remove" {
|
||||
client.remove(d);
|
||||
} else {
|
||||
client.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let kind = case["type"].as_str().unwrap_or_default();
|
||||
let grid = case["grid"].as_u64().unwrap_or(3) as usize;
|
||||
let mut stock = Stacked::default();
|
||||
for s in case["inventory"].as_array().into_iter().flatten() {
|
||||
if let Some(stack) = parse_stack(s.as_str().unwrap_or("-"))? {
|
||||
stock.account_simple(&stack, max(&stack));
|
||||
}
|
||||
}
|
||||
for s in case["slots"].as_array().into_iter().flatten() {
|
||||
if let Some(stack) = parse_stack(s.as_str().unwrap_or("-"))? {
|
||||
if kind == "crafting" {
|
||||
stock.account_simple(&stack, max(&stack));
|
||||
} else {
|
||||
stock.account_stack(&stack, max(&stack));
|
||||
}
|
||||
}
|
||||
}
|
||||
let book_type = match kind {
|
||||
"crafting" => BookType::Crafting,
|
||||
"furnace" => BookType::Furnace,
|
||||
"blast_furnace" => BookType::BlastFurnace,
|
||||
_ => BookType::Smoker,
|
||||
};
|
||||
let filtering = case["filtering"].as_bool().unwrap_or(false);
|
||||
for tab in book_type.tabs() {
|
||||
let collections = client.collections(&book, book_type, tab);
|
||||
let selected = |i: usize| match (&book.entries[i].display, book_type) {
|
||||
(Display::Furnace(_), BookType::Crafting) => false,
|
||||
(Display::Furnace(_), _) => true,
|
||||
(_, BookType::Crafting) => book.entries[i].fits(grid, grid),
|
||||
_ => false,
|
||||
};
|
||||
let craftable = |i: usize| selected(i) && book.can_craft(&book.entries[i], &stock);
|
||||
let visible = tab == Tab::Search
|
||||
|| collections
|
||||
.iter()
|
||||
.any(|c| c.entries.iter().any(|&i| selected(i)));
|
||||
let shown: Vec<_> = collections
|
||||
.iter()
|
||||
.filter(|c| c.entries.iter().any(|&i| selected(i)))
|
||||
.filter(|c| !filtering || c.entries.iter().any(|&i| craftable(i)))
|
||||
.collect();
|
||||
let name = match tab {
|
||||
Tab::Search => "search".to_owned(),
|
||||
Tab::Category(c) => c.name().to_owned(),
|
||||
};
|
||||
let _ = write!(
|
||||
out,
|
||||
"{name} {} pages={}",
|
||||
if visible { "shown" } else { "hidden" },
|
||||
shown.len().div_ceil(20)
|
||||
);
|
||||
for c in shown {
|
||||
let parts: Vec<String> = c
|
||||
.entries
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
format!(
|
||||
"{}{}{}",
|
||||
book.entries[i].display_id,
|
||||
if selected(i) { "s" } else { "" },
|
||||
if craftable(i) { "c" } else { "" }
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let _ = write!(out, " [{}]", parts.join(","));
|
||||
}
|
||||
out.push_str(" | ");
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
fs::write(args.get(3).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
//! The scoreboard model for differential tests against vanilla's `Scoreboard`
|
||||
//! (tools/test_scoreboard_parity.py): runs the same scripted operations as
|
||||
//! VanillaScoreboardOracle on `horizon_client::scoreboard::Scoreboard` and
|
||||
//! prints the same JSON lines (results, dumps, the packed save data before
|
||||
//! and after reloading it). With a vanilla output file it also reloads each
|
||||
//! case's vanilla NBT and packs it again (`vreload`).
|
||||
//!
|
||||
//! usage: scoreboard_fixture REGISTRIES.json INPUTS OUTPUT [VANILLA_OUTPUT]
|
||||
use horizon_client::{
|
||||
command::Registries,
|
||||
scoreboard::{
|
||||
self as sb, CollisionRule, Comp, NumberFormat, RenderType, Scoreboard, Visibility,
|
||||
canonical_component, criteria_by_name, criteria_read_only, criteria_render_type,
|
||||
},
|
||||
};
|
||||
use horizon_world::nbt::{self, NamedTag, Tag};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::{collections::BTreeMap, fs, io::Write};
|
||||
|
||||
fn canon(tag: &Tag) -> Value {
|
||||
match tag {
|
||||
Tag::Compound(c) => {
|
||||
let sorted: BTreeMap<String, &Tag> =
|
||||
c.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
|
||||
Value::Object(sorted.into_iter().map(|(k, v)| (k, canon(v))).collect())
|
||||
}
|
||||
Tag::List(l) => Value::Array(l.iter().map(canon).collect()),
|
||||
Tag::String(s) => Value::String(format!("'{}", s.to_string_lossy())),
|
||||
Tag::Byte(v) => Value::String(format!("{v}b")),
|
||||
Tag::Short(v) => Value::String(format!("{v}s")),
|
||||
Tag::Int(v) => Value::String(format!("{v}i")),
|
||||
Tag::Long(v) => Value::String(format!("{v}L")),
|
||||
Tag::Float(v) => Value::String(format!("f:{v:x}")),
|
||||
Tag::Double(v) => Value::String(format!("d:{v:x}")),
|
||||
Tag::IntArray(v) => json!({ "I;": v }),
|
||||
other => Value::String(format!("?{other:?}")),
|
||||
}
|
||||
}
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap_or(0))
|
||||
.collect()
|
||||
}
|
||||
fn encode(tag: &Tag) -> Vec<u8> {
|
||||
nbt::write_named(
|
||||
&NamedTag {
|
||||
name: "".into(),
|
||||
tag: tag.clone(),
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.expect("nbt")
|
||||
}
|
||||
fn decode(bytes: &[u8]) -> Tag {
|
||||
nbt::read_named(bytes, Default::default())
|
||||
.expect("nbt")
|
||||
.0
|
||||
.tag
|
||||
}
|
||||
|
||||
fn comp(v: Option<&Value>) -> Option<Comp> {
|
||||
v.filter(|v| !v.is_null()).cloned()
|
||||
}
|
||||
fn comp_json(c: Option<&Comp>) -> Value {
|
||||
c.map_or(Value::Null, canonical_component)
|
||||
}
|
||||
fn fmt_json(f: Option<&NumberFormat>) -> Value {
|
||||
f.map_or(Value::Null, NumberFormat::to_json)
|
||||
}
|
||||
fn fmt(v: Option<&Value>) -> Option<NumberFormat> {
|
||||
v.filter(|v| !v.is_null()).and_then(NumberFormat::from_json)
|
||||
}
|
||||
fn s<'a>(op: &'a Value, k: &str) -> &'a str {
|
||||
op[k].as_str().unwrap_or_default()
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
reg: Registries,
|
||||
}
|
||||
impl Fixture {
|
||||
fn criteria(&self, name: &str) -> Value {
|
||||
match criteria_by_name(name, &self.reg) {
|
||||
Ok(Some(c)) => Value::String(c),
|
||||
Ok(None) => Value::Null,
|
||||
Err(_) => Value::String("!invalid".into()),
|
||||
}
|
||||
}
|
||||
fn dump(&self, b: &Scoreboard, probes: &[Value]) -> Value {
|
||||
let objectives: Vec<Value> = b
|
||||
.objectives
|
||||
.iter()
|
||||
.map(|o| {
|
||||
json!({
|
||||
"name": o.name, "criteria": o.criteria, "display": comp_json(Some(&o.display_name)),
|
||||
"render": o.render_type.id(), "auto": o.display_auto_update,
|
||||
"format": fmt_json(o.number_format.as_ref()),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let stream: Vec<Value> = b
|
||||
.objectives_streamed()
|
||||
.iter()
|
||||
.map(|o| Value::String(o.name.clone()))
|
||||
.collect();
|
||||
let tracked = b.tracked();
|
||||
let mut lists = Map::new();
|
||||
for o in &b.objectives {
|
||||
let rows: Vec<Value> = b
|
||||
.list_scores(&o.name)
|
||||
.iter()
|
||||
.map(|e| {
|
||||
json!([
|
||||
e.owner,
|
||||
e.value,
|
||||
comp_json(e.display.as_ref()),
|
||||
fmt_json(e.number_format.as_ref())
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
lists.insert(o.name.clone(), Value::Array(rows));
|
||||
}
|
||||
let mut holders = Map::new();
|
||||
for h in &tracked {
|
||||
let mut per = Map::new();
|
||||
for o in &b.objectives {
|
||||
if let Some(sc) = b.score(h, &o.name) {
|
||||
per.insert(o.name.clone(), score_json(sc));
|
||||
}
|
||||
}
|
||||
holders.insert(h.clone(), Value::Object(per));
|
||||
}
|
||||
let teams: Vec<Value> = b
|
||||
.teams
|
||||
.iter()
|
||||
.map(|t| {
|
||||
json!({
|
||||
"name": t.name, "display": comp_json(Some(&t.display_name)), "color": t.color,
|
||||
"ff": t.allow_friendly_fire, "si": t.see_friendly_invisibles,
|
||||
"prefix": comp_json(Some(&t.prefix)), "suffix": comp_json(Some(&t.suffix)),
|
||||
"nametag": t.nametag_visibility.name(), "death": t.death_message_visibility.name(),
|
||||
"collision": t.collision_rule.name(),
|
||||
"players": t.players.iter().collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let teams_stream: Vec<Value> = b
|
||||
.teams_streamed()
|
||||
.iter()
|
||||
.map(|t| Value::String(t.name.clone()))
|
||||
.collect();
|
||||
let mut slots = Map::new();
|
||||
for slot in sb::display_slots() {
|
||||
if let Some(o) = b.display_objective(&slot) {
|
||||
slots.insert(slot, Value::String(o.name.clone()));
|
||||
}
|
||||
}
|
||||
let mut team_of = Map::new();
|
||||
for p in probes {
|
||||
let p = p.as_str().unwrap_or_default();
|
||||
team_of.insert(
|
||||
p.to_owned(),
|
||||
b.players_team(p)
|
||||
.map_or(Value::Null, |t| Value::String(t.name.clone())),
|
||||
);
|
||||
}
|
||||
json!({
|
||||
"objectives": objectives, "objectives_stream": stream, "tracked": tracked,
|
||||
"lists": lists, "holders": holders, "teams": teams, "teams_stream": teams_stream,
|
||||
"slots": slots, "team_of": team_of,
|
||||
})
|
||||
}
|
||||
fn apply(&self, b: &mut Scoreboard, op: &Value, probes: &[Value]) -> Value {
|
||||
let kind = s(op, "op");
|
||||
let holder = s(op, "holder");
|
||||
let dname = comp(op.get("dname"));
|
||||
match kind {
|
||||
"crit" => {
|
||||
let name = self.criteria(s(op, "name"));
|
||||
let mut o = json!({ "name": name });
|
||||
if let Some(n) = name.as_str().filter(|n| !n.starts_with('!')) {
|
||||
o["readonly"] = Value::Bool(criteria_read_only(n));
|
||||
o["render"] = Value::String(criteria_render_type(n).id().into());
|
||||
}
|
||||
o
|
||||
}
|
||||
"obj_add" => {
|
||||
let Some(criteria) = self
|
||||
.criteria(s(op, "criteria"))
|
||||
.as_str()
|
||||
.filter(|c| !c.starts_with('!'))
|
||||
.map(str::to_owned)
|
||||
else {
|
||||
return json!("bad");
|
||||
};
|
||||
if b.objective(s(op, "name")).is_some() {
|
||||
return json!("exists");
|
||||
}
|
||||
b.add_objective(
|
||||
s(op, "name"),
|
||||
&criteria,
|
||||
comp(op.get("display")).unwrap_or(Value::Null),
|
||||
RenderType::by_id(s(op, "render")),
|
||||
op["auto"].as_bool().unwrap_or(false),
|
||||
fmt(op.get("fmt")),
|
||||
);
|
||||
json!("ok")
|
||||
}
|
||||
"obj_rm" => {
|
||||
if b.objective(s(op, "name")).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.remove_objective(s(op, "name"));
|
||||
json!("ok")
|
||||
}
|
||||
"obj_mod" => {
|
||||
let Some(o) = b.objective_mut(s(op, "name")) else {
|
||||
return json!("missing");
|
||||
};
|
||||
let v = &op["value"];
|
||||
match s(op, "field") {
|
||||
"display" => o.display_name = v.clone(),
|
||||
"render" => o.render_type = RenderType::by_id(v.as_str().unwrap_or_default()),
|
||||
"auto" => o.display_auto_update = v.as_bool().unwrap_or(false),
|
||||
"fmt" => o.number_format = fmt(Some(v)),
|
||||
other => panic!("field {other}"),
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"slot" => {
|
||||
let name = op["name"].as_str();
|
||||
if let Some(n) = name
|
||||
&& b.objective(n).is_none()
|
||||
{
|
||||
return json!("missing");
|
||||
}
|
||||
b.set_display_objective(s(op, "slot"), name);
|
||||
json!("ok")
|
||||
}
|
||||
"set" | "add" | "get" | "lock" | "unlock" | "sdisplay" | "sfmt" => {
|
||||
let name = s(op, "name");
|
||||
let Some(criteria) = b.objective(name).map(|o| o.criteria.clone()) else {
|
||||
return json!("missing");
|
||||
};
|
||||
let force = op["force"].as_bool().unwrap_or(false);
|
||||
let writable = force || !criteria_read_only(&criteria);
|
||||
let current = b.get(holder, name);
|
||||
match kind {
|
||||
"set" | "add" => {
|
||||
if !writable {
|
||||
return json!("readonly");
|
||||
}
|
||||
let value = op["value"].as_i64().unwrap_or(0) as i32;
|
||||
let new = if kind == "add" {
|
||||
current.wrapping_add(value)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
b.set_with(holder, name, new, dname.as_ref());
|
||||
if kind == "add" {
|
||||
return json!(new);
|
||||
}
|
||||
}
|
||||
"get" => return json!(current),
|
||||
"lock" => b.score_mut(holder, name).locked = true,
|
||||
"unlock" => b.score_mut(holder, name).locked = false,
|
||||
"sdisplay" => b.score_mut(holder, name).display = comp(op.get("value")),
|
||||
"sfmt" => b.score_mut(holder, name).number_format = fmt(op.get("value")),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"info" => {
|
||||
let name = s(op, "name");
|
||||
if b.objective(name).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.score(holder, name).map_or(Value::Null, score_json)
|
||||
}
|
||||
"reset" => {
|
||||
match op["name"].as_str() {
|
||||
None => b.reset_all(holder),
|
||||
Some(name) => {
|
||||
if b.objective(name).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.reset_one(holder, name);
|
||||
}
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"all" => {
|
||||
let criteria = self.criteria(s(op, "criteria"));
|
||||
let criteria = criteria.as_str().unwrap_or_default();
|
||||
let value = op["value"].as_i64().unwrap_or(0) as i32;
|
||||
let k = s(op, "kind");
|
||||
b.for_all_objectives_with(criteria, holder, dname.as_ref(), |v| match k {
|
||||
"inc" => v.wrapping_add(1),
|
||||
"add" => v.wrapping_add(value),
|
||||
"set" => value,
|
||||
_ => 0,
|
||||
});
|
||||
json!("ok")
|
||||
}
|
||||
"team_add" => {
|
||||
if b.team(s(op, "name")).is_some() {
|
||||
return json!("exists");
|
||||
}
|
||||
b.add_team(s(op, "name"));
|
||||
json!("ok")
|
||||
}
|
||||
"team_rm" => {
|
||||
if b.team(s(op, "name")).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.remove_team(s(op, "name"));
|
||||
json!("ok")
|
||||
}
|
||||
"join" => {
|
||||
if b.team(s(op, "team")).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
json!(b.add_to_team(holder, s(op, "team")))
|
||||
}
|
||||
"leave" => json!(b.remove_from_team(holder)),
|
||||
"team_set" => {
|
||||
let Some(t) = b.team_mut(s(op, "name")) else {
|
||||
return json!("missing");
|
||||
};
|
||||
let v = &op["value"];
|
||||
let name = |v: &Value| v.as_str().unwrap_or_default().to_owned();
|
||||
match s(op, "field") {
|
||||
"display" => t.display_name = v.clone(),
|
||||
"color" => t.color = v.as_str().map(str::to_owned),
|
||||
"ff" => t.allow_friendly_fire = v.as_bool().unwrap_or(true),
|
||||
"si" => t.see_friendly_invisibles = v.as_bool().unwrap_or(true),
|
||||
"prefix" => t.prefix = comp(Some(v)).unwrap_or_else(|| sb::literal("")),
|
||||
"suffix" => t.suffix = comp(Some(v)).unwrap_or_else(|| sb::literal("")),
|
||||
"nametag" => {
|
||||
t.nametag_visibility = Visibility::by_name(&name(v)).expect("visibility")
|
||||
}
|
||||
"death" => {
|
||||
t.death_message_visibility =
|
||||
Visibility::by_name(&name(v)).expect("visibility")
|
||||
}
|
||||
"collision" => {
|
||||
t.collision_rule = CollisionRule::by_name(&name(v)).expect("collision")
|
||||
}
|
||||
other => panic!("field {other}"),
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"removed" => {
|
||||
b.entity_removed(holder);
|
||||
json!("ok")
|
||||
}
|
||||
"allied" => json!(b.allied(s(op, "a"), s(op, "b"))),
|
||||
"dump" => self.dump(b, probes),
|
||||
other => panic!("op {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn score_json(sc: &sb::Score) -> Value {
|
||||
json!({
|
||||
"value": sc.value, "locked": sc.locked, "display": comp_json(sc.display.as_ref()),
|
||||
"format": fmt_json(sc.number_format.as_ref()),
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let registries: Value =
|
||||
serde_json::from_str(&fs::read_to_string(&args[1]).expect("registries")).expect("json");
|
||||
let list = |k: &str| -> Vec<String> {
|
||||
registries[k]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let reg = Registries {
|
||||
items: list("items"),
|
||||
blocks: list("blocks")
|
||||
.into_iter()
|
||||
.map(|b| (b, Vec::new()))
|
||||
.collect(),
|
||||
entity_types: list("entity_types"),
|
||||
..Registries::default()
|
||||
};
|
||||
let fixture = Fixture { reg };
|
||||
let vanilla: BTreeMap<i64, String> = args
|
||||
.get(4)
|
||||
.and_then(|p| fs::read_to_string(p).ok())
|
||||
.map(|text| {
|
||||
text.lines()
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.filter_map(|v| Some((v["case"].as_i64()?, v["nbt"].as_str()?.to_owned())))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(&args[3]).expect("output"));
|
||||
for line in fs::read_to_string(&args[2]).expect("inputs").lines() {
|
||||
let case: Value = serde_json::from_str(line).expect("case");
|
||||
let probes = case["probes"].as_array().cloned().unwrap_or_default();
|
||||
let mut board = Scoreboard::default();
|
||||
let outs: Vec<Value> = case["ops"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|op| fixture.apply(&mut board, op, &probes))
|
||||
.collect();
|
||||
let packed = board.pack();
|
||||
let bytes = encode(&packed);
|
||||
let reloaded = Scoreboard::unpack(&decode(&bytes));
|
||||
let mut result = json!({
|
||||
"case": case["case"], "out": outs, "pack": canon(&packed), "nbt": hex(&bytes),
|
||||
"reload": canon(&reloaded.pack()), "reload_dump": fixture.dump(&reloaded, &probes),
|
||||
});
|
||||
if let Some(v) = case["case"].as_i64().and_then(|c| vanilla.get(&c)) {
|
||||
result["vreload"] = canon(&Scoreboard::unpack(&decode(&unhex(v))).pack());
|
||||
}
|
||||
writeln!(out, "{result}").expect("write");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Loom and crafter screen drawing for tools/test_screen_layout_parity.py:
|
||||
//! reads one JSON case per line and prints the `horizon_client::screen_layout`
|
||||
//! calls in the format of `VanillaLoomScreenOracle`.
|
||||
//!
|
||||
//! usage: screen_layout_fixture RESOURCES INPUT OUTPUT
|
||||
use horizon_client::{
|
||||
banner::{BannerLayer, Banners, banner_color},
|
||||
screen_layout::{self, CrafterView, LoomView, ScreenDraw},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fs, path::Path, sync::Arc};
|
||||
|
||||
fn draw_json(d: &ScreenDraw) -> Value {
|
||||
let round = |v: f32| ((v * 1e6).round() / 1e6) as f64;
|
||||
match d {
|
||||
ScreenDraw::Gradient { x1, y1 } => json!({"t": "gradient", "x1": x1, "y1": y1}),
|
||||
ScreenDraw::Blit {
|
||||
texture,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
tw,
|
||||
th,
|
||||
} => {
|
||||
json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h, "u": 0.0, "v": 0.0, "tw": tw, "th": th})
|
||||
}
|
||||
ScreenDraw::Sprite { id, x, y, w, h } => {
|
||||
json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h})
|
||||
}
|
||||
ScreenDraw::Banner {
|
||||
base,
|
||||
layers,
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
} => {
|
||||
let layers: Vec<Value> = layers
|
||||
.iter()
|
||||
.map(|l| json!([&*l.pattern, &*l.color]))
|
||||
.collect();
|
||||
json!({"t": "banner", "base": base, "layers": layers, "x0": x0, "y0": y0, "x1": x1, "y1": y1})
|
||||
}
|
||||
ScreenDraw::Tooltip { key } => json!({"t": "tooltip", "key": key}),
|
||||
ScreenDraw::SpriteOf { id } => {
|
||||
json!({"t": "sprite_of", "id": id.trim_start_matches("minecraft:")})
|
||||
}
|
||||
ScreenDraw::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}),
|
||||
ScreenDraw::Atlas { x0, y0, x1, y1, uv } => json!({
|
||||
"t": "atlas", "x0": x0, "y0": y0, "x1": x1, "y1": y1,
|
||||
"u0": round(uv[0]), "u1": round(uv[1]), "v0": round(uv[2]), "v1": round(uv[3])
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: screen_layout_fixture RESOURCES INPUT OUTPUT";
|
||||
let banners = Banners::load(Path::new(args.get(1).ok_or(usage)?));
|
||||
let input = fs::read_to_string(args.get(2).ok_or(usage)?)?;
|
||||
let mut out = String::new();
|
||||
for line in input.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let c: Value = serde_json::from_str(line)?;
|
||||
let int = |k: &str| c[k].as_i64().unwrap_or(0) as i32;
|
||||
let draws = if c["screen"] == "loom" {
|
||||
let patterns: Vec<Arc<str>> = c["patterns"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p.as_str().map(Arc::from))
|
||||
.collect();
|
||||
let layers: Vec<BannerLayer> = c["resultLayers"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|l| BannerLayer::new(l[0].as_str().unwrap_or(""), l[1].as_str().unwrap_or("")))
|
||||
.collect();
|
||||
let base = c["result"]
|
||||
.as_str()
|
||||
.and_then(banner_color)
|
||||
.unwrap_or("white");
|
||||
let dye = c["dyeStack"]
|
||||
.as_str()
|
||||
.and_then(|d| d.strip_prefix("minecraft:")?.strip_suffix("_dye"))
|
||||
.unwrap_or("white");
|
||||
let view = LoomView {
|
||||
width: int("width"),
|
||||
height: int("height"),
|
||||
left: int("left"),
|
||||
top: int("top"),
|
||||
has_banner: c["banner"].is_string(),
|
||||
has_dye: c["dye"].is_string(),
|
||||
has_pattern: c["pattern"].is_string(),
|
||||
patterns: &patterns,
|
||||
selected: int("selected"),
|
||||
display: c["display"].as_bool().unwrap_or(false),
|
||||
has_max: c["hasMax"].as_bool().unwrap_or(false),
|
||||
scroll: c["scroll"].as_f64().unwrap_or(0.0) as f32,
|
||||
start_row: int("startRow") as usize,
|
||||
result: c.get("resultLayers").map(|_| (base, layers.as_slice())),
|
||||
dye,
|
||||
mouse: (int("mouseX") as f32, int("mouseY") as f32),
|
||||
};
|
||||
screen_layout::loom(&view, &banners)
|
||||
} else {
|
||||
let mut disabled = [false; 9];
|
||||
for (i, d) in c["disabled"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.take(9)
|
||||
{
|
||||
disabled[i] = d.as_bool().unwrap_or(false);
|
||||
}
|
||||
screen_layout::crafter(&CrafterView {
|
||||
width: int("width"),
|
||||
height: int("height"),
|
||||
left: int("left"),
|
||||
top: int("top"),
|
||||
disabled,
|
||||
powered: c["powered"].as_bool().unwrap_or(false),
|
||||
})
|
||||
};
|
||||
let list: Vec<Value> = draws.iter().map(draw_json).collect();
|
||||
out += &json!({ "draws": list }).to_string();
|
||||
out.push('\n');
|
||||
}
|
||||
fs::write(args.get(3).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
//! The Rust side of tools/test_server_files_parity.py: reads each case
|
||||
//! directory the way VanillaServerFilesOracle does (server.properties,
|
||||
//! eula.txt, the four user lists and scripted list changes) and prints the
|
||||
//! same report. `server_files_probe CASES OUTPUT`.
|
||||
use horizon_client::server::{
|
||||
eula,
|
||||
java_properties::now_millis,
|
||||
properties::{DIFFICULTIES, GAME_MODES, ServerProperties, SystemEntropy},
|
||||
user_lists::{BanEntry, BanList, IpBanList, NameAndId, OpEntry, OpList, WhiteEntry, WhiteList},
|
||||
};
|
||||
use horizon_protocol::crypto::uuid_string;
|
||||
use std::{fmt::Write as _, path::Path};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let root = std::path::PathBuf::from(args.next().ok_or("CASES OUTPUT")?);
|
||||
let output = args.next().ok_or("OUTPUT")?;
|
||||
let mut cases: Vec<_> = std::fs::read_dir(&root)?
|
||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||
.filter(|p| p.is_dir())
|
||||
.collect();
|
||||
cases.sort();
|
||||
let mut out = String::new();
|
||||
for dir in cases {
|
||||
writeln!(out, "== {}", dir.file_name().unwrap().to_string_lossy())?;
|
||||
run_case(&dir, &mut out)?;
|
||||
}
|
||||
std::fs::write(output, out)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Files.readAllLines: split on \n, \r or \r\n.
|
||||
fn lines(text: &str) -> Vec<String> {
|
||||
let mut v: Vec<String> = text
|
||||
.replace("\r\n", "\n")
|
||||
.replace('\r', "\n")
|
||||
.split('\n')
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if v.last().is_some_and(String::is_empty) {
|
||||
v.pop();
|
||||
}
|
||||
v
|
||||
}
|
||||
fn latin1(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|&b| char::from(b)).collect()
|
||||
}
|
||||
fn has_key(text: &str, key: &str) -> bool {
|
||||
text.split('\n')
|
||||
.any(|l| l.trim_matches(|c: char| c <= ' ').starts_with(key))
|
||||
}
|
||||
|
||||
fn work(dir: &Path) -> std::io::Result<std::path::PathBuf> {
|
||||
let w = std::env::temp_dir().join(format!(
|
||||
"server-files-{}-{}",
|
||||
std::process::id(),
|
||||
dir.file_name().unwrap().to_string_lossy()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
std::fs::create_dir_all(&w)?;
|
||||
for e in std::fs::read_dir(dir)? {
|
||||
let e = e?;
|
||||
std::fs::copy(e.path(), w.join(e.file_name()))?;
|
||||
}
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
fn run_case(dir: &Path, out: &mut String) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let w = work(dir)?;
|
||||
let props = w.join("server.properties");
|
||||
if dir.join("server.properties").exists() || dir.join("properties.default").exists() {
|
||||
let before = std::fs::read(&props)
|
||||
.map(|b| latin1(&b))
|
||||
.unwrap_or_default();
|
||||
match ServerProperties::from_file(&props, &mut SystemEntropy::default()) {
|
||||
Ok(p) => {
|
||||
print_properties(&p, &before, out)?;
|
||||
p.store(&props)?;
|
||||
writeln!(out, "stored:")?;
|
||||
for (i, line) in lines(&std::fs::read_to_string(&props)?)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let line = if i == 1 && line.starts_with('#') {
|
||||
"#DATE".to_owned()
|
||||
} else if line.starts_with("management-server-secret=")
|
||||
&& !has_key(&before, "management-server-secret")
|
||||
{
|
||||
"management-server-secret=<random>".to_owned()
|
||||
} else {
|
||||
line
|
||||
};
|
||||
writeln!(out, "{line}")?;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let class = e.split(':').next().unwrap_or("");
|
||||
writeln!(out, "ERROR {class}")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if dir.join("eula.txt").exists() || dir.join("eula.missing").exists() {
|
||||
let path = w.join("eula.txt");
|
||||
let agreed = eula::agreed(&path).unwrap_or(false);
|
||||
writeln!(out, "eula agreed={agreed}")?;
|
||||
if let Ok(bytes) = std::fs::read(&path) {
|
||||
for (i, line) in lines(&latin1(&bytes)).into_iter().enumerate() {
|
||||
if i == 1 && line.starts_with('#') {
|
||||
writeln!(out, "#DATE")?;
|
||||
} else {
|
||||
writeln!(out, "{line}")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ops = OpList::new(w.join("ops.json"));
|
||||
let mut white = WhiteList::new(w.join("whitelist.json"));
|
||||
let mut bans = BanList::new(w.join("banned-players.json"));
|
||||
let mut ips = IpBanList::new(w.join("banned-ips.json"));
|
||||
let mut any = false;
|
||||
macro_rules! load {
|
||||
($list:expr, $name:literal) => {
|
||||
if $list.file.exists() {
|
||||
any = true;
|
||||
if let Err(_) = $list.load() {
|
||||
writeln!(
|
||||
out,
|
||||
"{} load ERROR com.google.gson.JsonSyntaxException",
|
||||
$name
|
||||
)?;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
load!(ops, "ops");
|
||||
load!(white, "whitelist");
|
||||
load!(bans, "banned-players");
|
||||
load!(ips, "banned-ips");
|
||||
if let Ok(actions) = std::fs::read_to_string(dir.join("actions.txt")) {
|
||||
any = true;
|
||||
for line in actions.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let a: Vec<&str> = line.split('\t').collect();
|
||||
let user = |n: &str, u: &str| NameAndId {
|
||||
id: horizon_client::server::properties::parse_uuid(u).unwrap(),
|
||||
name: n.to_owned(),
|
||||
};
|
||||
fn ban<T>(
|
||||
user: T,
|
||||
created: &str,
|
||||
source: &str,
|
||||
expires: &str,
|
||||
reason: &str,
|
||||
) -> BanEntry<T> {
|
||||
let date = |s: &str| (s != "-").then(|| s.parse::<i64>().unwrap());
|
||||
BanEntry {
|
||||
user,
|
||||
created: date(created).unwrap_or_else(now_millis),
|
||||
source: if source != "-" {
|
||||
source.to_owned()
|
||||
} else {
|
||||
"(Unknown)".into()
|
||||
},
|
||||
expires: date(expires),
|
||||
reason: (reason != "-").then(|| reason.to_owned()),
|
||||
}
|
||||
}
|
||||
let r = match a[0] {
|
||||
"op" => ops.add(OpEntry {
|
||||
user: user(a[1], a[2]),
|
||||
level: a[3].parse::<i32>()?.clamp(0, 4),
|
||||
bypasses_player_limit: a[4].eq_ignore_ascii_case("true"),
|
||||
}),
|
||||
"deop" => ops.remove(&user(a[1], a[2])),
|
||||
"white" => white.add(WhiteEntry {
|
||||
user: user(a[1], a[2]),
|
||||
}),
|
||||
"unwhite" => white.remove(&user(a[1], a[2])),
|
||||
"ban" => bans.add(ban(user(a[1], a[2]), a[3], a[4], a[5], a[6])),
|
||||
"pardon" => bans.remove(&user(a[1], a[2])),
|
||||
"banip" => ips.add(ban(a[1].to_owned(), a[2], a[3], a[4], a[5])),
|
||||
"pardonip" => ips.remove(&a[1].to_owned()),
|
||||
"isbanned" => bans.contains(&user(a[1], a[2])),
|
||||
"isop" => ops.get(&user(a[1], a[2])).is_some(),
|
||||
other => return Err(format!("unknown action {other}").into()),
|
||||
};
|
||||
writeln!(out, "action {} {r}", a[0])?;
|
||||
}
|
||||
}
|
||||
if any {
|
||||
for (name, json) in [
|
||||
("ops", ops.to_json()),
|
||||
("whitelist", white.to_json()),
|
||||
("banned-players", bans.to_json()),
|
||||
("banned-ips", ips.to_json()),
|
||||
] {
|
||||
writeln!(out, "{name}:\n{json}")?;
|
||||
}
|
||||
let mut names: Vec<String> = ops.entries().iter().map(|e| e.user.name.clone()).collect();
|
||||
names.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
|
||||
writeln!(out, "op users {}", names.join(","))?;
|
||||
let mut names: Vec<String> = white
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|e| e.user.name.clone())
|
||||
.collect();
|
||||
names.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
|
||||
writeln!(out, "white users {}", names.join(","))?;
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_properties(p: &ServerProperties, before: &str, out: &mut String) -> std::fmt::Result {
|
||||
let secret = if has_key(before, "management-server-secret") {
|
||||
p.management_server_secret.clone()
|
||||
} else {
|
||||
"<random>".into()
|
||||
};
|
||||
let pack = p.resource_pack.as_ref().map_or_else(
|
||||
|| "none".to_owned(),
|
||||
|i| {
|
||||
format!(
|
||||
"{} {} {} {} {}",
|
||||
uuid_string(i.id),
|
||||
i.url,
|
||||
i.hash,
|
||||
i.required,
|
||||
i.prompt.is_some()
|
||||
)
|
||||
},
|
||||
);
|
||||
let opt_bool = |b: Option<bool>| b.map_or_else(|| "null".to_owned(), |b| b.to_string());
|
||||
let rows: Vec<(&str, String)> = vec![
|
||||
("online-mode", p.online_mode.to_string()),
|
||||
(
|
||||
"prevent-proxy-connections",
|
||||
p.prevent_proxy_connections.to_string(),
|
||||
),
|
||||
("server-ip", p.server_ip.clone()),
|
||||
("allow-flight", p.allow_flight.to_string()),
|
||||
("motd", p.motd.clone()),
|
||||
("enable-code-of-conduct", p.code_of_conduct.to_string()),
|
||||
("bug-report-link", p.bug_report_link.clone()),
|
||||
("force-gamemode", p.force_game_mode.to_string()),
|
||||
("enforce-whitelist", p.enforce_whitelist.to_string()),
|
||||
("difficulty", DIFFICULTIES[p.difficulty as usize].to_owned()),
|
||||
("gamemode", GAME_MODES[p.game_mode as usize].to_owned()),
|
||||
("level-name", p.level_name.clone()),
|
||||
("server-port", p.server_port.to_string()),
|
||||
(
|
||||
"management-server-enabled",
|
||||
p.management_server_enabled.to_string(),
|
||||
),
|
||||
("management-server-host", p.management_server_host.clone()),
|
||||
(
|
||||
"management-server-port",
|
||||
p.management_server_port.to_string(),
|
||||
),
|
||||
("management-server-secret", secret),
|
||||
(
|
||||
"management-server-tls-enabled",
|
||||
p.management_server_tls_enabled.to_string(),
|
||||
),
|
||||
(
|
||||
"management-server-tls-keystore",
|
||||
p.management_server_tls_keystore.clone(),
|
||||
),
|
||||
(
|
||||
"management-server-tls-keystore-password",
|
||||
p.management_server_tls_keystore_password.clone(),
|
||||
),
|
||||
(
|
||||
"management-server-allowed-origins",
|
||||
p.management_server_allowed_origins.clone(),
|
||||
),
|
||||
(
|
||||
"announce-player-achievements",
|
||||
opt_bool(p.announce_player_achievements),
|
||||
),
|
||||
("enable-query", p.enable_query.to_string()),
|
||||
("query.port", p.query_port.to_string()),
|
||||
("enable-rcon", p.enable_rcon.to_string()),
|
||||
("rcon.port", p.rcon_port.to_string()),
|
||||
("rcon.password", p.rcon_password.clone()),
|
||||
("hardcore", p.hardcore.to_string()),
|
||||
("use-native-transport", p.use_native_transport.to_string()),
|
||||
("spawn-protection", p.spawn_protection.to_string()),
|
||||
("op-permission-level", p.op_permission_level.to_string()),
|
||||
(
|
||||
"function-permission-level",
|
||||
p.function_permission_level.to_string(),
|
||||
),
|
||||
("max-tick-time", p.max_tick_time.to_string()),
|
||||
(
|
||||
"max-chained-neighbor-updates",
|
||||
p.max_chained_neighbor_updates.to_string(),
|
||||
),
|
||||
("rate-limit", p.rate_limit.to_string()),
|
||||
(
|
||||
"command-spam-threshold-seconds",
|
||||
p.command_spam_threshold_seconds.to_string(),
|
||||
),
|
||||
(
|
||||
"chat-spam-threshold-seconds",
|
||||
p.chat_spam_threshold_seconds.to_string(),
|
||||
),
|
||||
("view-distance", p.view_distance.to_string()),
|
||||
("simulation-distance", p.simulation_distance.to_string()),
|
||||
("max-players", p.max_players.to_string()),
|
||||
(
|
||||
"network-compression-threshold",
|
||||
p.network_compression_threshold.to_string(),
|
||||
),
|
||||
("broadcast-rcon-to-ops", p.broadcast_rcon_to_ops.to_string()),
|
||||
(
|
||||
"broadcast-console-to-ops",
|
||||
p.broadcast_console_to_ops.to_string(),
|
||||
),
|
||||
("max-world-size", p.max_world_size.to_string()),
|
||||
("sync-chunk-writes", p.sync_chunk_writes.to_string()),
|
||||
("region-file-compression", p.region_file_compression.clone()),
|
||||
("enable-jmx-monitoring", p.enable_jmx_monitoring.to_string()),
|
||||
("enable-status", p.enable_status.to_string()),
|
||||
("hide-online-players", p.hide_online_players.to_string()),
|
||||
(
|
||||
"entity-broadcast-range-percentage",
|
||||
p.entity_broadcast_range_percentage.to_string(),
|
||||
),
|
||||
("text-filtering-config", p.text_filtering_config.clone()),
|
||||
(
|
||||
"text-filtering-version",
|
||||
p.text_filtering_version.to_string(),
|
||||
),
|
||||
("player-idle-timeout", p.player_idle_timeout.to_string()),
|
||||
(
|
||||
"status-heartbeat-interval",
|
||||
p.status_heartbeat_interval.to_string(),
|
||||
),
|
||||
("white-list", p.white_list.to_string()),
|
||||
(
|
||||
"enforce-secure-profile",
|
||||
p.enforce_secure_profile.to_string(),
|
||||
),
|
||||
("log-ips", p.log_ips.to_string()),
|
||||
(
|
||||
"pause-when-empty-seconds",
|
||||
p.pause_when_empty_seconds.to_string(),
|
||||
),
|
||||
("accepts-transfers", p.accepts_transfers.to_string()),
|
||||
(
|
||||
"seed",
|
||||
if p.random_seed {
|
||||
"<random>".into()
|
||||
} else {
|
||||
p.seed.to_string()
|
||||
},
|
||||
),
|
||||
("generate-structures", p.generate_structures.to_string()),
|
||||
("resource-pack", pack),
|
||||
("initial-enabled-packs", p.initial_enabled_packs.join("|")),
|
||||
("initial-disabled-packs", p.initial_disabled_packs.join("|")),
|
||||
];
|
||||
for (k, v) in rows {
|
||||
writeln!(out, "{k}={v}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The subtitle overlay for differential tests against vanilla's
|
||||
//! `SubtitleOverlay` (tools/test_subtitle_parity.py): replays each case's
|
||||
//! sound plays, clock changes and frames through
|
||||
//! `horizon_client::subtitles` and prints every frame's fills and texts with
|
||||
//! their pose, in VanillaSubtitleOracle's JSON lines.
|
||||
//!
|
||||
//! usage: subtitle_fixture RESOURCES INPUTS OUTPUT
|
||||
use horizon_client::{
|
||||
hud::HudAtlas,
|
||||
hud_layout::{GuiDraw, IDENTITY, background_color, pose_apply},
|
||||
hud_overlays::{SubtitleFrame, SubtitleOverlay},
|
||||
lang,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fs, io::Write, path::PathBuf};
|
||||
|
||||
fn vec3(v: &Value) -> [f64; 3] {
|
||||
std::array::from_fn(|i| v[i].as_f64().unwrap_or(0.0))
|
||||
}
|
||||
fn pose(m: [f32; 6]) -> Value {
|
||||
json!(m)
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
let [root, inputs, output] = args.as_slice() else {
|
||||
return Err("usage: subtitle_fixture RESOURCES INPUTS OUTPUT".into());
|
||||
};
|
||||
lang::set(lang::Language::load(&[root], lang::DEFAULT));
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let c: Value = serde_json::from_str(line)?;
|
||||
let mut overlay = SubtitleOverlay::default();
|
||||
let mut now = 0i64;
|
||||
let mut frames = Vec::new();
|
||||
for op in c["ops"].as_array().into_iter().flatten() {
|
||||
match op["op"].as_str().unwrap_or_default() {
|
||||
// Util.getMillis: nanoseconds / 1_000_000.
|
||||
"time" => now = op["ms"].as_i64().unwrap_or(0),
|
||||
"play" => {
|
||||
if overlay.listening() {
|
||||
let range = op["range"].as_f64().map_or(f32::INFINITY, |r| r as f32);
|
||||
overlay.on_play(
|
||||
op["key"].as_str(),
|
||||
vec3(&op["at"]),
|
||||
range,
|
||||
op["looping"].as_bool().unwrap_or(false),
|
||||
now,
|
||||
);
|
||||
}
|
||||
}
|
||||
"frame" => {
|
||||
let frame = SubtitleFrame {
|
||||
show: op["show"].as_bool().unwrap_or(false),
|
||||
position: vec3(&op["pos"]),
|
||||
forward: vec3(&op["forward"]),
|
||||
up: vec3(&op["up"]),
|
||||
multiplier: op["mult"].as_f64().unwrap_or(1.0),
|
||||
background: background_color(
|
||||
op["chat_only"].as_bool().unwrap_or(true),
|
||||
op["opacity"].as_f64().unwrap_or(0.5),
|
||||
0.8,
|
||||
),
|
||||
width: op["w"].as_i64().unwrap_or(0) as i32,
|
||||
height: op["h"].as_i64().unwrap_or(0) as i32,
|
||||
};
|
||||
let mut stack = vec![IDENTITY];
|
||||
let mut draws = Vec::new();
|
||||
let calls = overlay.extract(&frame, &atlas.font, now);
|
||||
if !calls.is_empty() {
|
||||
draws.push(json!({"type": "stratum"}));
|
||||
}
|
||||
for d in calls {
|
||||
let m = *stack.last().unwrap_or(&IDENTITY);
|
||||
match d {
|
||||
GuiDraw::Push(ops) => {
|
||||
let mut top = m;
|
||||
for op in ops {
|
||||
pose_apply(&mut top, op);
|
||||
}
|
||||
stack.push(top);
|
||||
}
|
||||
GuiDraw::Pop => {
|
||||
stack.pop();
|
||||
}
|
||||
GuiDraw::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => draws.push(json!({
|
||||
"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1,
|
||||
"color": format!("{color:x}"), "pose": pose(m),
|
||||
})),
|
||||
GuiDraw::Text {
|
||||
text,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => draws.push(json!({
|
||||
"type": "text", "text": text.plain(), "x": x, "y": y,
|
||||
"color": format!("{color:x}"), "shadow": shadow, "pose": pose(m),
|
||||
})),
|
||||
other => return Err(format!("unexpected draw {other:?}").into()),
|
||||
}
|
||||
}
|
||||
frames.push(Value::Array(draws));
|
||||
}
|
||||
other => return Err(format!("op {other}").into()),
|
||||
}
|
||||
}
|
||||
writeln!(out, "{}", json!({"case": c["case"], "frames": frames}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Headless transport for the player list parity gate: builds each case's
|
||||
//! scoreboard (teams, `list` objective, scores), listed players, header and
|
||||
//! footer, replays its frames through `horizon_client::tab_list` and writes
|
||||
//! the draw calls in vanilla's GuiGraphicsExtractor terms (text as styled
|
||||
//! runs, faces as skin blits).
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
component,
|
||||
hud::HudAtlas,
|
||||
hud_layout::GuiDraw,
|
||||
lang,
|
||||
scoreboard::{NumberFormat, RenderType, Scoreboard},
|
||||
tab_list::{self, TabInputs, TabList, TabPlayer},
|
||||
text::Text,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufWriter, Write},
|
||||
path::PathBuf,
|
||||
};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn text(v: &Value) -> Option<Text> {
|
||||
(!v.is_null()).then(|| component::to_text(v, &mut |_| Text::empty()))
|
||||
}
|
||||
fn format(v: &Value) -> Option<NumberFormat> {
|
||||
match v["type"].as_str()? {
|
||||
"blank" => Some(NumberFormat::Blank),
|
||||
"styled" => Some(NumberFormat::Styled(v["style"].clone())),
|
||||
"fixed" => Some(NumberFormat::Fixed(v["value"].clone())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn runs(t: &Text) -> Value {
|
||||
let mut out: Vec<(String, Value)> = Vec::new();
|
||||
for (c, s) in t.chars() {
|
||||
let key = json!([
|
||||
s.color.map_or(-1, i64::from),
|
||||
s.is_bold(),
|
||||
s.is_italic(),
|
||||
s.underlined == Some(true),
|
||||
s.strikethrough == Some(true),
|
||||
s.obfuscated == Some(true)
|
||||
]);
|
||||
match out.last_mut() {
|
||||
Some((run, k)) if *k == key => run.push(c),
|
||||
_ => out.push((c.to_string(), key)),
|
||||
}
|
||||
}
|
||||
out.into_iter().map(|(r, k)| json!([r, k])).collect()
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
let [root, inputs, output] = args.as_slice() else {
|
||||
return Err("usage: tab_list_fixture RESOURCES INPUTS OUTPUT".into());
|
||||
};
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
lang::set(lang::Language::load(&[root], "en_us"));
|
||||
let font = &atlas.font;
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let c: Value = serde_json::from_str(line)?;
|
||||
let mut board = Scoreboard::default();
|
||||
for t in c["teams"].as_array().into_iter().flatten() {
|
||||
let name = t["name"].as_str().unwrap_or("");
|
||||
let team = board.add_team(name);
|
||||
team.color = t["color"].as_str().map(str::to_owned);
|
||||
team.prefix = t["prefix"].clone();
|
||||
team.suffix = t["suffix"].clone();
|
||||
for m in t["members"].as_array().into_iter().flatten() {
|
||||
board.add_to_team(m.as_str().unwrap_or(""), name);
|
||||
}
|
||||
}
|
||||
let objective_name = c["objective"]["name"].as_str().map(str::to_owned);
|
||||
if let Some(name) = &objective_name {
|
||||
let hearts = c["objective"]["renderType"] == "hearts";
|
||||
board.add_objective(
|
||||
name,
|
||||
"dummy",
|
||||
Value::String("x".into()),
|
||||
if hearts {
|
||||
RenderType::Hearts
|
||||
} else {
|
||||
RenderType::Integer
|
||||
},
|
||||
false,
|
||||
format(&c["objective"]["numberFormat"]),
|
||||
);
|
||||
}
|
||||
let mut players = Vec::new();
|
||||
let mut upside = Vec::new();
|
||||
for p in c["players"].as_array().into_iter().flatten() {
|
||||
let uuid =
|
||||
u128::from_str_radix(&p["uuid"].as_str().unwrap_or("0").replace('-', ""), 16)?;
|
||||
let name = p["name"].as_str().unwrap_or("").to_owned();
|
||||
if p["inLevel"].as_bool().unwrap_or(false) && (name == "Dinnerbone" || name == "Grumm")
|
||||
{
|
||||
upside.push(uuid);
|
||||
}
|
||||
let mut player = TabPlayer::new(uuid, name);
|
||||
player.game_mode = p["gameMode"].as_i64().unwrap_or(0) as i32;
|
||||
player.latency = p["latency"].as_i64().unwrap_or(0) as i32;
|
||||
player.display_name = (!p["displayName"].is_null()).then(|| p["displayName"].clone());
|
||||
player.list_order = p["listOrder"].as_i64().unwrap_or(0) as i32;
|
||||
player.show_hat = p["showHat"].as_bool().unwrap_or(true);
|
||||
players.push(player);
|
||||
}
|
||||
let mut list = TabList::default();
|
||||
list.header = text(&c["header"]);
|
||||
list.footer = text(&c["footer"]);
|
||||
let background = tab_list::row_background(
|
||||
c["backgroundForChatOnly"].as_bool().unwrap_or(true),
|
||||
c["opacity"].as_f64().unwrap_or(0.5),
|
||||
);
|
||||
let mut frames = Vec::new();
|
||||
for f in c["frames"].as_array().into_iter().flatten() {
|
||||
if let Some(obj) = &objective_name {
|
||||
for (holder, v) in f["scores"].as_object().into_iter().flatten() {
|
||||
let s = board.score_mut(holder, obj);
|
||||
s.value = v["value"].as_i64().unwrap_or(0) as i32;
|
||||
s.number_format = format(&v["format"]);
|
||||
}
|
||||
for r in f["reset"].as_array().into_iter().flatten() {
|
||||
board.reset_one(r.as_str().unwrap_or(""), obj);
|
||||
}
|
||||
}
|
||||
let visible = f["visible"].as_bool().unwrap_or(false);
|
||||
list.set_visible(visible);
|
||||
let mut draws = Vec::new();
|
||||
if visible {
|
||||
let up = |id: u128| upside.contains(&id);
|
||||
let inputs = TabInputs {
|
||||
players: &players,
|
||||
board: &board,
|
||||
objective: objective_name.as_deref().and_then(|n| board.objective(n)),
|
||||
screen_width: c["width"].as_i64().unwrap_or(0) as i32,
|
||||
online_mode: c["onlineMode"].as_bool().unwrap_or(false),
|
||||
gui_ticks: f["tick"].as_i64().unwrap_or(0),
|
||||
background,
|
||||
upside_down: &up,
|
||||
};
|
||||
for d in list.layout(&inputs, font) {
|
||||
draws.push(match d {
|
||||
GuiDraw::Fill { x0, y0, x1, y1, color } => {
|
||||
json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color as i32})
|
||||
}
|
||||
GuiDraw::Sprite { sprite, x, y, w, h, .. } => {
|
||||
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h})
|
||||
}
|
||||
GuiDraw::Text { text, x, y, color, shadow } => json!({
|
||||
"type": "text", "runs": runs(&text), "x": x, "y": y, "color": color as i32, "shadow": shadow
|
||||
}),
|
||||
GuiDraw::Blit { texture, x, y, w, h, uv, src, tex, color, .. } => {
|
||||
let a = [x as f64, y as f64, f64::from(uv[0]), f64::from(uv[1]), w as f64, h as f64,
|
||||
src[0] as f64, src[1] as f64, tex[0] as f64, tex[1] as f64];
|
||||
json!({"type": "blit", "texture": texture, "args": a, "color": color as i32})
|
||||
}
|
||||
other => json!({"type": "unexpected", "draw": format!("{other:?}")}),
|
||||
});
|
||||
}
|
||||
}
|
||||
frames.push(Value::Array(draws));
|
||||
}
|
||||
writeln!(out, "{}", json!({ "frames": frames }))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Team rules in gameplay for differential tests against vanilla
|
||||
//! (tools/test_team_rules_parity.py): friendly fire, alliances, collision
|
||||
//! rules, seeing invisible team mates and name tag visibility, from
|
||||
//! `horizon_client::scoreboard`, in VanillaTeamRulesOracle's JSON lines.
|
||||
//!
|
||||
//! usage: team_rules_fixture INPUTS OUTPUT
|
||||
use horizon_client::scoreboard::{self as sb, CollisionRule, NameView, Scoreboard, Visibility};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fs, io::Write};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(&args[2]).expect("output"));
|
||||
for line in fs::read_to_string(&args[1]).expect("inputs").lines() {
|
||||
let c: Value = serde_json::from_str(line).expect("case");
|
||||
let mut board = Scoreboard::default();
|
||||
for name in ["A", "B"] {
|
||||
let o = &c[name];
|
||||
let t = board.add_team(name);
|
||||
t.allow_friendly_fire = o["ff"].as_bool().unwrap_or(true);
|
||||
t.see_friendly_invisibles = o["si"].as_bool().unwrap_or(true);
|
||||
t.collision_rule =
|
||||
CollisionRule::by_name(o["collision"].as_str().unwrap_or("")).expect("rule");
|
||||
t.nametag_visibility =
|
||||
Visibility::by_name(o["nametag"].as_str().unwrap_or("")).expect("visibility");
|
||||
}
|
||||
let team = |k: &str| c[k].as_str().and_then(|n| board.team(n));
|
||||
let flag = |k: &str| c[k].as_bool().unwrap_or(false);
|
||||
let (own, other, viewer) = (team("own"), team("other"), team("viewer"));
|
||||
let invisible =
|
||||
sb::invisible_to(other, viewer, flag("viewer_spectator"), flag("invisible"));
|
||||
let view = NameView {
|
||||
discrete: flag("discrete"),
|
||||
distance_sqr: c["distance"].as_f64().unwrap_or(0.0),
|
||||
invisible_to_viewer: invisible,
|
||||
hud_hidden: flag("hud_hidden"),
|
||||
is_camera: flag("camera_is_entity"),
|
||||
is_vehicle: flag("vehicle"),
|
||||
};
|
||||
let r = json!({
|
||||
"case": c["case"],
|
||||
"damage": sb::teams_allow_damage(own, other),
|
||||
"allied": sb::teams_allied(own, other),
|
||||
"pushes": !flag("spectator") && sb::pushable_by(own, other, flag("pushable")),
|
||||
"invisible": invisible,
|
||||
"name": sb::name_shown(other, viewer, view),
|
||||
});
|
||||
writeln!(out, "{r}").expect("write");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Headless transport for the world border parity gate: replays each case's
|
||||
//! border changes, ticks and frames through `horizon_client::worldborder`,
|
||||
//! `border_render` and `hud_overlays::vignette`, and writes what the
|
||||
//! vanilla renderer computes (bounds, fade, wall buffer, transforms, walls
|
||||
//! drawn, vignette colour) with floats as raw bits.
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
border_render::{self, BorderRenderState, BorderRenderer},
|
||||
hud_layout::GuiDraw,
|
||||
hud_overlays,
|
||||
worldborder::{BorderStatus, WorldBorder},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufWriter, Write},
|
||||
};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn floats(v: &[f32]) -> Value {
|
||||
v.iter().map(|f| f.to_bits() as i32).collect()
|
||||
}
|
||||
fn doubles(v: &[f64]) -> Value {
|
||||
v.iter().map(|f| f.to_bits() as i64).collect()
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let [inputs, output] = args.as_slice() else {
|
||||
return Err("usage: world_border_render_fixture INPUTS OUTPUT".into());
|
||||
};
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let c: Value = serde_json::from_str(line)?;
|
||||
let f = |v: &Value| v.as_f64().unwrap_or(0.0);
|
||||
let mut border = WorldBorder::default();
|
||||
border.warning_distance = c["warningBlocks"].as_i64().unwrap_or(0) as i32;
|
||||
border.warning_time = c["warningTime"].as_i64().unwrap_or(0) as i32;
|
||||
border.set_absolute_max_size(c["absoluteMaxSize"].as_i64().unwrap_or(0) as i32);
|
||||
border.set_center([f(&c["centerX"]), f(&c["centerZ"])]);
|
||||
border.set_size(f(&c["size"]));
|
||||
let mut renderer = BorderRenderer::default();
|
||||
let mut state = BorderRenderState::default();
|
||||
let mut frames = Vec::new();
|
||||
for op in c["ops"].as_array().into_iter().flatten() {
|
||||
match op["op"].as_str().unwrap_or("") {
|
||||
"tick" => (0..op["n"].as_i64().unwrap_or(0)).for_each(|_| border.tick()),
|
||||
"lerp" => border.lerp_between(
|
||||
f(&op["from"]),
|
||||
f(&op["to"]),
|
||||
op["ticks"].as_i64().unwrap_or(0),
|
||||
),
|
||||
"size" => border.set_size(f(&op["size"])),
|
||||
"center" => border.set_center([f(&op["x"]), f(&op["z"])]),
|
||||
"warning" => {
|
||||
border.warning_distance = op["blocks"].as_i64().unwrap_or(0) as i32;
|
||||
border.warning_time = op["time"].as_i64().unwrap_or(0) as i32;
|
||||
}
|
||||
"invalidate" => renderer.invalidate(),
|
||||
"frame" => {
|
||||
let partial = f(&op["partial"]) as f32;
|
||||
let p = &op["camera"];
|
||||
let camera = [f(&p[0]), f(&p[1]), f(&p[2])];
|
||||
let distance = f(&op["renderDistance"]);
|
||||
let millis = op["millis"].as_i64().unwrap_or(0);
|
||||
let status = match border.status() {
|
||||
BorderStatus::Growing => "GROWING",
|
||||
BorderStatus::Shrinking => "SHRINKING",
|
||||
BorderStatus::Stationary => "STATIONARY",
|
||||
};
|
||||
let mut frame = json!({
|
||||
"bounds": doubles(&border.bounds_at(partial)),
|
||||
"sizes": doubles(&[border.size(), border.target_size(), border.lerp_speed(), border.distance(camera[0], camera[2])]),
|
||||
"lerpTime": border.remaining_ticks(),
|
||||
"status": status,
|
||||
});
|
||||
border_render::extract(&border, partial, camera, distance, &mut state);
|
||||
frame["alpha"] = doubles(&[state.alpha]);
|
||||
frame["tint"] = json!(state.tint as i32);
|
||||
let drawn =
|
||||
renderer.prepare(&state, camera, distance, f(&op["depthFar"]) as f32);
|
||||
frame["drawn"] = json!(drawn);
|
||||
frame["rebuilt"] = json!(renderer.take_rebuilt());
|
||||
if drawn {
|
||||
frame["vertices"] = floats(&renderer.vertices.concat());
|
||||
let t = renderer.transforms(&state, camera, millis);
|
||||
frame["color"] = floats(&t.color);
|
||||
frame["offset"] = floats(&t.model_offset);
|
||||
frame["texture"] = floats(&[t.texture_offset, t.texture_offset]);
|
||||
frame["sides"] = json!(BorderRenderer::sides(&state, camera, distance));
|
||||
}
|
||||
let warning = border.warning_strength(camera[0], camera[2]);
|
||||
let vignette =
|
||||
hud_overlays::vignette(427, 240, f(&op["vignette"]) as f32, warning);
|
||||
let color = match vignette {
|
||||
GuiDraw::Blit { color, .. } => color,
|
||||
_ => 0,
|
||||
};
|
||||
frame["vignetteColor"] = json!(color as i32);
|
||||
frames.push(frame);
|
||||
}
|
||||
other => return Err(format!("unknown op {other}").into()),
|
||||
}
|
||||
}
|
||||
writeln!(out, "{}", json!({ "frames": frames }))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,13 +2,14 @@
|
||||
#![forbid(unsafe_code)]
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
os::unix::net::UnixStream,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, ExitCode, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use horizon_client::control::UnixStream;
|
||||
|
||||
const USAGE: &str = "usage: horizon-ctl [--socket PATH] COMMAND [ARGS...]
|
||||
|
||||
Local commands:
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// The world border wall (core/world_border): camera-relative wall quads
|
||||
// moved by the model offset, the forcefield texture scrolled by the texture
|
||||
// offset and modulated by the status colour and fade.
|
||||
struct Globals {
|
||||
view_proj: mat4x4<f32>,
|
||||
}
|
||||
struct Border {
|
||||
color: vec4<f32>,
|
||||
// xyz: model offset, w: texture translation (u and v)
|
||||
offset: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var forcefield: texture_2d<f32>;
|
||||
@group(0) @binding(2) var forcefield_sampler: sampler;
|
||||
@group(0) @binding(3) var<uniform> border: Border;
|
||||
struct Out {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
@vertex fn vs_border(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>) -> Out {
|
||||
var out: Out;
|
||||
out.clip = globals.view_proj * vec4(position + border.offset.xyz, 1.0);
|
||||
out.uv = uv + vec2(border.offset.w);
|
||||
return out;
|
||||
}
|
||||
@fragment fn fs_border(in: Out) -> @location(0) vec4<f32> {
|
||||
let color = textureSample(forcefield, forcefield_sampler, in.uv);
|
||||
if color.a == 0.0 {
|
||||
discard;
|
||||
}
|
||||
return color * border.color;
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! The world border wall (`WorldBorderRenderer`, `WorldBorderRenderState`):
|
||||
//! which border the camera is near, the wall's fade and status colour, the
|
||||
//! cached vertex buffer of the four walls, the scrolling texture transform
|
||||
//! and which walls are drawn. Kept free of GPU types so the parity fixture
|
||||
//! can compare every value with vanilla's renderer.
|
||||
use crate::worldborder::{WorldBorder, jclamp, jmax, jmin, status_color};
|
||||
|
||||
/// `WorldBorderRenderer.RENDERING_OFFSET`.
|
||||
const OFFSET: f64 = 0.01;
|
||||
|
||||
/// `WorldBorderRenderState`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct BorderRenderState {
|
||||
pub min_x: f64,
|
||||
pub max_x: f64,
|
||||
pub min_z: f64,
|
||||
pub max_z: f64,
|
||||
/// `BorderStatus.getColor`, set only when the wall is visible.
|
||||
pub tint: u32,
|
||||
pub alpha: f64,
|
||||
}
|
||||
impl BorderRenderState {
|
||||
/// `closestBorder`: the four walls by distance from (x, z), nearest
|
||||
/// first (a stable sort of north, south, west, east), as
|
||||
/// `Direction.get2DDataValue` side indices and distances.
|
||||
pub fn closest_border(&self, x: f64, z: f64) -> [(usize, f64); 4] {
|
||||
let mut sides = [
|
||||
(2, z - self.min_z),
|
||||
(0, self.max_z - z),
|
||||
(1, x - self.min_x),
|
||||
(3, self.max_x - x),
|
||||
];
|
||||
// Comparator.comparingDouble: Double.compare order, stable.
|
||||
sides.sort_by(|a, b| java_double_compare(a.1, b.1));
|
||||
sides
|
||||
}
|
||||
}
|
||||
/// `Double.compare`.
|
||||
fn java_double_compare(a: f64, b: f64) -> std::cmp::Ordering {
|
||||
use std::cmp::Ordering::*;
|
||||
if a < b {
|
||||
Less
|
||||
} else if a > b {
|
||||
Greater
|
||||
} else {
|
||||
let bits = |v: f64| {
|
||||
if v.is_nan() {
|
||||
0x7ff8_0000_0000_0000u64 as i64
|
||||
} else {
|
||||
v.to_bits() as i64
|
||||
}
|
||||
};
|
||||
bits(a).cmp(&bits(b))
|
||||
}
|
||||
}
|
||||
|
||||
/// `WorldBorderRenderer.extract`.
|
||||
pub fn extract(
|
||||
border: &WorldBorder,
|
||||
partial: f32,
|
||||
camera: [f64; 3],
|
||||
render_distance: f64,
|
||||
state: &mut BorderRenderState,
|
||||
) {
|
||||
let [min_x, min_z, max_x, max_z] = border.bounds_at(partial);
|
||||
state.min_x = min_x;
|
||||
state.max_x = max_x;
|
||||
state.min_z = min_z;
|
||||
state.max_z = max_z;
|
||||
let (x, z) = (camera[0], camera[2]);
|
||||
let deep_inside = x < max_x - render_distance
|
||||
&& x > min_x + render_distance
|
||||
&& z < max_z - render_distance
|
||||
&& z > min_z + render_distance;
|
||||
let far_outside = x < min_x - render_distance
|
||||
|| x > max_x + render_distance
|
||||
|| z < min_z - render_distance
|
||||
|| z > max_z + render_distance;
|
||||
if !deep_inside && !far_outside {
|
||||
let alpha = 1.0 - border.distance(x, z) / render_distance;
|
||||
state.alpha = jclamp(alpha.powf(4.0), 0.0, 1.0);
|
||||
state.tint = status_color(border.status());
|
||||
} else {
|
||||
state.alpha = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// One `POSITION_TEX` vertex of the wall buffer: position relative to the
|
||||
/// buffer origin and texture coordinates.
|
||||
pub type BorderVertex = [f32; 5];
|
||||
|
||||
/// What `WorldBorderRenderer.prepareDynamicTransforms` writes: the colour
|
||||
/// modulator, the model offset of the buffer origin from the camera and
|
||||
/// the texture matrix translation (both u and v).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BorderTransforms {
|
||||
pub color: [f32; 4],
|
||||
pub model_offset: [f32; 3],
|
||||
pub texture_offset: f32,
|
||||
}
|
||||
|
||||
/// `WorldBorderRenderer`'s cached wall buffer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BorderRenderer {
|
||||
needs_rebuild: bool,
|
||||
/// Set when `prepare` rebuilt the buffer (cleared by [`Self::take_rebuilt`]).
|
||||
rebuilt: bool,
|
||||
last_min_x: f64,
|
||||
last_min_z: f64,
|
||||
last_border: [f64; 4],
|
||||
/// Four quads: south, west, north, east (`get2DDataValue` order).
|
||||
pub vertices: [BorderVertex; 16],
|
||||
}
|
||||
impl Default for BorderRenderer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
needs_rebuild: true,
|
||||
rebuilt: false,
|
||||
last_min_x: 0.0,
|
||||
last_min_z: 0.0,
|
||||
last_border: [0.0; 4],
|
||||
vertices: [[0.0; 5]; 16],
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Mth.floor(double)`.
|
||||
fn floor(v: f64) -> i32 {
|
||||
let i = v as i32;
|
||||
if v < f64::from(i) { i - 1 } else { i }
|
||||
}
|
||||
/// `Mth.ceil(double)`.
|
||||
fn ceil(v: f64) -> i32 {
|
||||
let i = v as i32;
|
||||
if v > f64::from(i) { i + 1 } else { i }
|
||||
}
|
||||
/// `Mth.frac(double)`.
|
||||
fn frac(v: f64) -> f64 {
|
||||
v - v.floor()
|
||||
}
|
||||
impl BorderRenderer {
|
||||
/// `invalidate`: rebuild on the next prepare (e.g. after a resource reload).
|
||||
pub fn invalidate(&mut self) {
|
||||
self.needs_rebuild = true;
|
||||
}
|
||||
/// `prepare`: rebuilds the buffer when the border moved; returns whether
|
||||
/// the wall is drawn this frame.
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
state: &BorderRenderState,
|
||||
camera: [f64; 3],
|
||||
render_distance: f64,
|
||||
depth_far: f32,
|
||||
) -> bool {
|
||||
if state.alpha <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
let half_height = depth_far;
|
||||
let v0 = (-frac(camera[1] * 0.5)) as f32;
|
||||
let v1 = v0 + half_height;
|
||||
let border = [state.min_x, state.min_z, state.max_x, state.max_z];
|
||||
if self.needs_rebuild || border != self.last_border {
|
||||
self.rebuild(
|
||||
state,
|
||||
render_distance,
|
||||
camera[2],
|
||||
camera[0],
|
||||
half_height,
|
||||
v1,
|
||||
v0,
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `rebuildWorldBorderBuffer`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn rebuild(
|
||||
&mut self,
|
||||
state: &BorderRenderState,
|
||||
render_distance: f64,
|
||||
camera_z: f64,
|
||||
camera_x: f64,
|
||||
h: f32,
|
||||
v1: f32,
|
||||
v0: f32,
|
||||
) {
|
||||
let border_min_x = state.min_x + OFFSET;
|
||||
let border_max_x = state.max_x - OFFSET;
|
||||
let border_min_z = state.min_z + OFFSET;
|
||||
let border_max_z = state.max_z - OFFSET;
|
||||
let min_z = jmax(f64::from(floor(camera_z - render_distance)), border_min_z);
|
||||
let max_z = jmin(f64::from(ceil(camera_z + render_distance)), border_max_z);
|
||||
let u0z = (floor(min_z) & 1) as f32 * 0.5;
|
||||
let u1z = (max_z - min_z) as f32 / 2.0;
|
||||
let min_x = jmax(f64::from(floor(camera_x - render_distance)), border_min_x);
|
||||
let max_x = jmin(f64::from(ceil(camera_x + render_distance)), border_max_x);
|
||||
let u0x = (floor(min_x) & 1) as f32 * 0.5;
|
||||
let u1x = (max_x - min_x) as f32 / 2.0;
|
||||
let (dx, dz) = ((max_x - min_x) as f32, (max_z - min_z) as f32);
|
||||
let south = (border_max_z - min_z) as f32;
|
||||
let east = (border_max_x - min_x) as f32;
|
||||
self.vertices = [
|
||||
[0.0, -h, south, u0x, v1],
|
||||
[dx, -h, south, u1x + u0x, v1],
|
||||
[dx, h, south, u1x + u0x, v0],
|
||||
[0.0, h, south, u0x, v0],
|
||||
[0.0, -h, 0.0, u0z, v1],
|
||||
[0.0, -h, dz, u1z + u0z, v1],
|
||||
[0.0, h, dz, u1z + u0z, v0],
|
||||
[0.0, h, 0.0, u0z, v0],
|
||||
[dx, -h, 0.0, u0x, v1],
|
||||
[0.0, -h, 0.0, u1x + u0x, v1],
|
||||
[0.0, h, 0.0, u1x + u0x, v0],
|
||||
[dx, h, 0.0, u0x, v0],
|
||||
[east, -h, dz, u0z, v1],
|
||||
[east, -h, 0.0, u1z + u0z, v1],
|
||||
[east, h, 0.0, u1z + u0z, v0],
|
||||
[east, h, dz, u0z, v0],
|
||||
];
|
||||
self.last_border = [state.min_x, state.min_z, state.max_x, state.max_z];
|
||||
self.last_min_x = min_x;
|
||||
self.last_min_z = min_z;
|
||||
self.needs_rebuild = false;
|
||||
self.rebuilt = true;
|
||||
}
|
||||
/// Whether the buffer was rebuilt since the last call (it must be
|
||||
/// uploaded again).
|
||||
pub fn take_rebuilt(&mut self) -> bool {
|
||||
std::mem::take(&mut self.rebuilt)
|
||||
}
|
||||
/// `prepareDynamicTransforms` at `Util.getMillis()` = `millis`.
|
||||
pub fn transforms(
|
||||
&self,
|
||||
state: &BorderRenderState,
|
||||
camera: [f64; 3],
|
||||
millis: i64,
|
||||
) -> BorderTransforms {
|
||||
let channel = |shift: u32| ((state.tint >> shift) & 0xFF) as f32 / 255.0;
|
||||
let offset = (millis % 3000) as f32 / 3000.0;
|
||||
BorderTransforms {
|
||||
color: [channel(16), channel(8), channel(0), state.alpha as f32],
|
||||
model_offset: [
|
||||
(self.last_min_x - camera[0]) as f32,
|
||||
(-camera[1]) as f32,
|
||||
(self.last_min_z - camera[2]) as f32,
|
||||
],
|
||||
texture_offset: offset,
|
||||
}
|
||||
}
|
||||
/// `draw`: the walls within the render distance, nearest first, as side
|
||||
/// indices into [`Self::vertices`] (four vertices each).
|
||||
pub fn sides(state: &BorderRenderState, camera: [f64; 3], render_distance: f64) -> Vec<usize> {
|
||||
state
|
||||
.closest_border(camera[0], camera[2])
|
||||
.into_iter()
|
||||
.filter(|&(_, d)| d < render_distance)
|
||||
.map(|(side, _)| side)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn near_wall_is_drawn_and_tinted() {
|
||||
let mut border = WorldBorder::default();
|
||||
border.set_size(100.0);
|
||||
let mut state = BorderRenderState::default();
|
||||
let camera = [40.0, 64.0, 0.0];
|
||||
extract(&border, 0.0, camera, 128.0, &mut state);
|
||||
assert!(state.alpha > 0.0);
|
||||
assert_eq!(state.tint, 0x20A0FF);
|
||||
let mut r = BorderRenderer::default();
|
||||
assert!(r.prepare(&state, camera, 128.0, 512.0));
|
||||
// East wall first (10 blocks away), then north and south, then west.
|
||||
assert_eq!(
|
||||
BorderRenderer::sides(&state, camera, 128.0),
|
||||
vec![3, 2, 0, 1]
|
||||
);
|
||||
let t = r.transforms(&state, camera, 4500);
|
||||
assert_eq!(t.texture_offset, 0.5);
|
||||
// Far inside a huge border, nothing is drawn.
|
||||
border.set_size(10_000.0);
|
||||
extract(&border, 0.0, camera, 128.0, &mut state);
|
||||
assert_eq!(state.alpha, 0.0);
|
||||
assert!(!r.prepare(&state, camera, 128.0, 512.0));
|
||||
}
|
||||
}
|
||||
@@ -1652,15 +1652,26 @@ impl ArgType {
|
||||
reader.skip();
|
||||
}
|
||||
let id = &reader.string[start..reader.cursor];
|
||||
if !crate::scoreboard::criteria_exists(id, reg) {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
// ObjectiveCriteria.byName: statistics resolve to their canonical name.
|
||||
match crate::scoreboard::criteria_by_name(id, reg) {
|
||||
Ok(Some(canonical)) => Arg::Str(canonical),
|
||||
Ok(None) => {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Err(_) => {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
Arg::Str(id.to_owned())
|
||||
}
|
||||
ArgType::ScoreboardSlot => {
|
||||
let name = reader.read_unquoted_string();
|
||||
|
||||
@@ -97,7 +97,7 @@ impl Crafter {
|
||||
.count() as i32
|
||||
}
|
||||
/// `canPlaceItem`: a hopper fills the smallest stacks first.
|
||||
pub fn can_place(&self, slot: usize, stack: &ItemStack, max_stack: u32) -> bool {
|
||||
pub fn can_place(&self, slot: usize, _stack: &ItemStack, max_stack: u32) -> bool {
|
||||
if slot >= 9 || self.disabled[slot] {
|
||||
return false;
|
||||
}
|
||||
@@ -112,7 +112,7 @@ impl Crafter {
|
||||
&& match &self.items[i] {
|
||||
None => true,
|
||||
Some(other) => {
|
||||
other.count < current.count && other.same_item_same_components(stack)
|
||||
other.count < current.count && other.same_item_same_components(current)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -208,6 +208,7 @@ impl BlockEntity {
|
||||
}
|
||||
let size = match name {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
|
||||
n if n.ends_with("copper_chest") => 27,
|
||||
"minecraft:hopper" => 5,
|
||||
"minecraft:dispenser" | "minecraft:dropper" => 9,
|
||||
n if n.ends_with("shulker_box") => 27,
|
||||
@@ -219,6 +220,7 @@ impl BlockEntity {
|
||||
pub fn id_for_block(name: &str) -> Option<&'static str> {
|
||||
Some(match name {
|
||||
"minecraft:chest" => "minecraft:chest",
|
||||
n if n.ends_with("copper_chest") => "minecraft:chest",
|
||||
"minecraft:trapped_chest" => "minecraft:trapped_chest",
|
||||
"minecraft:barrel" => "minecraft:barrel",
|
||||
"minecraft:hopper" => "minecraft:hopper",
|
||||
|
||||
@@ -5,12 +5,61 @@
|
||||
//! that depend on a later frame (screenshots, benchmarks) arrive when ready.
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
os::unix::net::{UnixListener, UnixStream},
|
||||
path::{Path, PathBuf},
|
||||
sync::mpsc,
|
||||
thread,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
pub use std::os::unix::net::{UnixListener, UnixStream};
|
||||
#[cfg(not(unix))]
|
||||
pub use unsupported::{UnixListener, UnixStream};
|
||||
|
||||
/// Windows' standard library has no Unix domain sockets: there the control
|
||||
/// socket reports itself unavailable and the game runs without it.
|
||||
#[cfg(not(unix))]
|
||||
mod unsupported {
|
||||
use std::{io, path::Path};
|
||||
|
||||
fn unavailable() -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"the control socket needs Unix domain sockets (Linux or macOS)",
|
||||
)
|
||||
}
|
||||
pub struct UnixStream;
|
||||
impl UnixStream {
|
||||
pub fn connect<P: AsRef<Path>>(_: P) -> io::Result<Self> {
|
||||
Err(unavailable())
|
||||
}
|
||||
pub fn try_clone(&self) -> io::Result<Self> {
|
||||
Err(unavailable())
|
||||
}
|
||||
}
|
||||
impl io::Read for UnixStream {
|
||||
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
|
||||
Err(unavailable())
|
||||
}
|
||||
}
|
||||
impl io::Write for UnixStream {
|
||||
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
|
||||
Err(unavailable())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub struct UnixListener;
|
||||
impl UnixListener {
|
||||
pub fn bind<P: AsRef<Path>>(_: P) -> io::Result<Self> {
|
||||
Err(unavailable())
|
||||
}
|
||||
pub fn incoming(&self) -> std::iter::Empty<io::Result<UnixStream>> {
|
||||
std::iter::empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One command line from a client, with the channel for its JSON reply.
|
||||
pub struct Request {
|
||||
pub line: String,
|
||||
|
||||
@@ -56,6 +56,39 @@ impl Ingredient {
|
||||
self.0.contains(&*stack.item)
|
||||
}
|
||||
}
|
||||
/// `PlacementInfo`: the ingredients to find and, per recipe slot, the index
|
||||
/// of its ingredient (`slotsToIngredientIndex`, -1 for an empty slot). Empty
|
||||
/// when the recipe is impossible to place.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Placement {
|
||||
pub ingredients: Vec<Ingredient>,
|
||||
pub slots: Vec<i32>,
|
||||
/// A `ShapedRecipe`'s width and height (the others fill the grid).
|
||||
pub shaped: Option<(usize, usize)>,
|
||||
}
|
||||
impl Placement {
|
||||
/// `PlacementInfo.createFromOptionals` (and `create` with no empty slots).
|
||||
pub fn of(cells: Vec<Option<Ingredient>>, shaped: Option<(usize, usize)>) -> Self {
|
||||
let mut out = Self {
|
||||
shaped,
|
||||
..Self::default()
|
||||
};
|
||||
for cell in cells {
|
||||
match cell {
|
||||
Some(i) if i.0.is_empty() => return Self::default(),
|
||||
Some(i) => {
|
||||
out.slots.push(out.ingredients.len() as i32);
|
||||
out.ingredients.push(i);
|
||||
}
|
||||
None => out.slots.push(-1),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn impossible(&self) -> bool {
|
||||
self.slots.is_empty()
|
||||
}
|
||||
}
|
||||
/// A recipe result: `ItemStackTemplate` (`id`, `count`, `components`), with the
|
||||
/// id optional for the transmuting recipes that keep the input's item.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -1319,56 +1352,114 @@ impl Recipes {
|
||||
map_scale,
|
||||
};
|
||||
for (name, recipe) in &self.crafting {
|
||||
let result = match recipe {
|
||||
Recipe::Special(special) => {
|
||||
if !special.matches(&ctx, &input) {
|
||||
continue;
|
||||
}
|
||||
special.assemble(&ctx, &input)
|
||||
}
|
||||
Recipe::Shaped {
|
||||
width,
|
||||
height,
|
||||
cells,
|
||||
result,
|
||||
} => {
|
||||
if *width != input.width
|
||||
|| *height != input.height
|
||||
|| cells.iter().flatten().count() != input.count()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let matches = |mirror: bool| {
|
||||
(0..*height).all(|y| {
|
||||
(0..*width).all(|x| {
|
||||
let rx = if mirror { width - 1 - x } else { x };
|
||||
match (&cells[y * width + rx], input.get(x, y)) {
|
||||
(None, None) => true,
|
||||
(Some(i), Some(s)) => i.test(s),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
if !(matches(false) || matches(true)) {
|
||||
continue;
|
||||
}
|
||||
Some(result.create())
|
||||
}
|
||||
Recipe::Shapeless {
|
||||
ingredients,
|
||||
result,
|
||||
} => {
|
||||
if !matches_all(ingredients, &input.stacks()) {
|
||||
continue;
|
||||
}
|
||||
Some(result.create())
|
||||
}
|
||||
};
|
||||
return result.map(|r| (name.as_str(), r));
|
||||
if let Some(result) = Self::assemble_if_matches(&ctx, &input, recipe) {
|
||||
return result.map(|r| (name.as_str(), r));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `Recipe.matches` then `assemble` for one recipe: None when it does
|
||||
/// not match, Some(None) when it matches with nothing to make.
|
||||
fn assemble_if_matches(
|
||||
ctx: &Context,
|
||||
input: &Input,
|
||||
recipe: &Recipe,
|
||||
) -> Option<Option<ItemStack>> {
|
||||
match recipe {
|
||||
Recipe::Special(special) => special
|
||||
.matches(ctx, input)
|
||||
.then(|| special.assemble(ctx, input)),
|
||||
Recipe::Shaped {
|
||||
width,
|
||||
height,
|
||||
cells,
|
||||
result,
|
||||
} => {
|
||||
if *width != input.width
|
||||
|| *height != input.height
|
||||
|| cells.iter().flatten().count() != input.count()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let matches = |mirror: bool| {
|
||||
(0..*height).all(|y| {
|
||||
(0..*width).all(|x| {
|
||||
let rx = if mirror { width - 1 - x } else { x };
|
||||
match (&cells[y * width + rx], input.get(x, y)) {
|
||||
(None, None) => true,
|
||||
(Some(i), Some(s)) => i.test(s),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
(matches(false) || matches(true)).then(|| Some(result.create()))
|
||||
}
|
||||
Recipe::Shapeless {
|
||||
ingredients,
|
||||
result,
|
||||
} => matches_all(ingredients, &input.stacks()).then(|| Some(result.create())),
|
||||
}
|
||||
}
|
||||
/// `recipe.matches(craftSlots.asCraftInput())` for one recipe by id
|
||||
/// (`minecraft:name`).
|
||||
pub fn recipe_matches(&self, id: &str, grid: &[Option<ItemStack>], size: usize) -> bool {
|
||||
let name = id.trim_start_matches("minecraft:");
|
||||
let Some((_, recipe)) = self.crafting.iter().find(|(n, _)| n == name) else {
|
||||
return false;
|
||||
};
|
||||
let Some(input) = Input::of(grid, size) else {
|
||||
return false;
|
||||
};
|
||||
let ctx = Context {
|
||||
recipes: self,
|
||||
map_scale: &|_| None,
|
||||
};
|
||||
Self::assemble_if_matches(&ctx, &input, recipe).is_some()
|
||||
}
|
||||
/// `Recipe.placementInfo` of a crafting or cooking recipe by id; None for
|
||||
/// an unknown id, an empty placement when it is impossible to place.
|
||||
pub fn placement(&self, id: &str) -> Option<Placement> {
|
||||
let name = id.trim_start_matches("minecraft:");
|
||||
if let Some(c) = self.cooking.iter().find(|c| c.id == name) {
|
||||
return Some(Placement::of(vec![Some(c.ingredient.clone())], None));
|
||||
}
|
||||
let (_, recipe) = self.crafting.iter().find(|(n, _)| n == name)?;
|
||||
Some(match recipe {
|
||||
Recipe::Shaped {
|
||||
width,
|
||||
height,
|
||||
cells,
|
||||
..
|
||||
} => Placement::of(cells.clone(), Some((*width, *height))),
|
||||
Recipe::Shapeless { ingredients, .. } => {
|
||||
Placement::of(ingredients.iter().cloned().map(Some).collect(), None)
|
||||
}
|
||||
Recipe::Special(Special::Transmute {
|
||||
input,
|
||||
material,
|
||||
max,
|
||||
..
|
||||
}) => {
|
||||
let mut list = vec![Some(input.clone())];
|
||||
list.extend(std::iter::repeat_n(Some(material.clone()), *max));
|
||||
Placement::of(list, None)
|
||||
}
|
||||
Recipe::Special(Special::Dye { target, dye, .. }) => {
|
||||
Placement::of(vec![Some(target.clone()), Some(dye.clone())], None)
|
||||
}
|
||||
Recipe::Special(Special::Imbue {
|
||||
source, material, ..
|
||||
}) => Placement::of(
|
||||
(0..9)
|
||||
.map(|i| Some(if i == 4 { source } else { material }.clone()))
|
||||
.collect(),
|
||||
None,
|
||||
),
|
||||
// CustomRecipe.placementInfo: NOT_PLACEABLE.
|
||||
Recipe::Special(_) => Placement::default(),
|
||||
})
|
||||
}
|
||||
/// `Recipe.getRemainingItems` placed on the `size`x`size` grid: an item's
|
||||
/// crafting remainder (buckets, bottles), the patterned banner a duplicate
|
||||
/// keeps and the written book a clone keeps.
|
||||
|
||||
@@ -135,6 +135,16 @@ pub fn instant(id: &str, amp: i32, scale: f64) -> Option<EffectAction> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// What an omen's `applyEffectTick` decided.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum OmenTick {
|
||||
/// It returned true: the effect counts down as usual.
|
||||
Continue,
|
||||
/// It returned false: the effect goes.
|
||||
Remove,
|
||||
/// It added this effect, then returned false.
|
||||
Add(EffectInstance),
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PlayerEffects {
|
||||
pub list: Vec<EffectInstance>,
|
||||
@@ -160,6 +170,71 @@ impl PlayerEffects {
|
||||
pub fn clear(&mut self) {
|
||||
self.list.clear();
|
||||
}
|
||||
/// `LivingEntity.tickEffects` (server part) with the omens' effect ticks:
|
||||
/// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect`
|
||||
/// (on its last tick). Returns the actions to apply, in order, and
|
||||
/// whether Raid Omen was newly added.
|
||||
///
|
||||
/// Bad Omen turning into a new Raid Omen adds an entry to the map being
|
||||
/// iterated: vanilla's iterator then throws a
|
||||
/// `ConcurrentModificationException`, which `tickEffects` swallows. Bad
|
||||
/// Omen stays (not counted down) and the effects after it are not
|
||||
/// ticked; the next tick refreshes Raid Omen and drops Bad Omen.
|
||||
pub fn tick_with(
|
||||
&mut self,
|
||||
omen: &mut dyn FnMut(&EffectInstance) -> OmenTick,
|
||||
) -> (Vec<EffectAction>, bool) {
|
||||
self.tick_count = self.tick_count.wrapping_add(1);
|
||||
let mut actions = Vec::new();
|
||||
let mut added = false;
|
||||
let mut i = 0;
|
||||
while i < self.list.len() {
|
||||
let e = &self.list[i];
|
||||
if !(e.infinite() || e.duration > 0) {
|
||||
self.list.remove(i);
|
||||
continue;
|
||||
}
|
||||
let t = if e.infinite() {
|
||||
self.tick_count
|
||||
} else {
|
||||
e.duration
|
||||
};
|
||||
if let Some(a) = periodic(e.id, t, e.amplifier) {
|
||||
actions.push(a);
|
||||
}
|
||||
let answer = match e.id {
|
||||
"bad_omen" => omen(e),
|
||||
"raid_omen" if t == 1 => omen(e),
|
||||
_ => OmenTick::Continue,
|
||||
};
|
||||
match answer {
|
||||
OmenTick::Continue => {}
|
||||
OmenTick::Remove => {
|
||||
self.list.remove(i);
|
||||
continue;
|
||||
}
|
||||
OmenTick::Add(effect) => {
|
||||
if let Some(existing) = self.list.iter_mut().find(|x| x.id == effect.id) {
|
||||
existing.update(&effect);
|
||||
self.list.remove(i);
|
||||
continue;
|
||||
}
|
||||
self.list.push(effect);
|
||||
added = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let e = &mut self.list[i];
|
||||
e.tick_down();
|
||||
e.downgrade();
|
||||
if e.infinite() || e.duration > 0 {
|
||||
i += 1;
|
||||
} else {
|
||||
self.list.remove(i);
|
||||
}
|
||||
}
|
||||
(actions, added)
|
||||
}
|
||||
/// `LivingEntity.tickEffects` (server part): actions to apply, in order.
|
||||
pub fn tick(&mut self) -> Vec<EffectAction> {
|
||||
self.tick_count = self.tick_count.wrapping_add(1);
|
||||
@@ -325,6 +400,45 @@ impl StatusFlags {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bad_omen_in_a_village_becomes_raid_omen_over_two_ticks() {
|
||||
let mut fx = PlayerEffects::default();
|
||||
fx.add(EffectInstance::new("bad_omen", 100, 1));
|
||||
fx.add(EffectInstance::new("speed", 50, 0));
|
||||
let mut convert = |e: &EffectInstance| match e.id {
|
||||
"bad_omen" => OmenTick::Add(EffectInstance::new("raid_omen", 600, e.amplifier)),
|
||||
_ => OmenTick::Continue,
|
||||
};
|
||||
// The first tick adds Raid Omen and stops there (the iterator's
|
||||
// ConcurrentModificationException): Bad Omen and Speed stay as they were.
|
||||
let (_, added) = fx.tick_with(&mut convert);
|
||||
assert!(added);
|
||||
assert_eq!(fx.get("bad_omen").unwrap().duration, 100);
|
||||
assert_eq!(fx.get("speed").unwrap().duration, 50);
|
||||
assert_eq!(fx.get("raid_omen").unwrap().duration, 600);
|
||||
// The second refreshes Raid Omen and drops Bad Omen.
|
||||
let (_, added) = fx.tick_with(&mut convert);
|
||||
assert!(!added);
|
||||
assert!(fx.get("bad_omen").is_none());
|
||||
assert_eq!(fx.get("speed").unwrap().duration, 49);
|
||||
assert_eq!(fx.get("raid_omen").unwrap().amplifier, 1);
|
||||
}
|
||||
#[test]
|
||||
fn raid_omen_acts_on_its_last_tick() {
|
||||
let mut fx = PlayerEffects::default();
|
||||
fx.add(EffectInstance::new("raid_omen", 2, 0));
|
||||
let mut seen = Vec::new();
|
||||
let mut watch = |e: &EffectInstance| {
|
||||
seen.push(e.duration);
|
||||
OmenTick::Remove
|
||||
};
|
||||
fx.tick_with(&mut watch);
|
||||
assert!(fx.get("raid_omen").is_some());
|
||||
fx.tick_with(&mut watch);
|
||||
assert!(fx.get("raid_omen").is_none());
|
||||
assert_eq!(seen, vec![1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_keeps_stronger_and_hides_longer() {
|
||||
let mut fx = PlayerEffects::default();
|
||||
|
||||
@@ -432,6 +432,17 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
// CopperGolem.addAdditionalSaveData.
|
||||
"minecraft:copper_golem" => {
|
||||
map.insert(
|
||||
"next_weather_age".into(),
|
||||
Tag::Long(m.extra.vector[0] as i64),
|
||||
);
|
||||
map.insert(
|
||||
"weather_state".into(),
|
||||
string(crate::mobs::copper_golem::WEATHER[m.extra.variant.min(3) as usize]),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
crate::mobs::raider::write_nbt(m, map);
|
||||
@@ -739,6 +750,21 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
if m.species() == crate::mobs::Species::Sniffer {
|
||||
crate::mobs::sniffer::from_nbt(&mut m, tag);
|
||||
}
|
||||
if m.species() == crate::mobs::Species::CopperGolem {
|
||||
// CopperGolem.readAdditionalSaveData: -1 (unset) when missing.
|
||||
m.extra.vector[0] = match tag.get("next_weather_age") {
|
||||
Some(Tag::Long(v)) => *v as f64,
|
||||
_ => -1.0,
|
||||
};
|
||||
let weather = match tag.get("weather_state") {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => String::new(),
|
||||
};
|
||||
m.extra.variant = crate::mobs::copper_golem::WEATHER
|
||||
.iter()
|
||||
.position(|w| *w == weather)
|
||||
.unwrap_or(0) as u8;
|
||||
}
|
||||
m.extra.leash_pending = crate::mobs::leash::pending_from_nbt(tag.get("leash"));
|
||||
if m.species() == crate::mobs::Species::Warden {
|
||||
// The brain starts afresh: a minute before it digs back down.
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Iteration order of fastutil's `Object2ObjectOpenHashMap<String, _>` (open
|
||||
//! Iteration order of the Java hash collections vanilla's scoreboard keeps
|
||||
//! its names in: fastutil's `Object2ObjectOpenHashMap<String, _>` (open
|
||||
//! addressing with linear probing, backward-shift deletion and rehashing at
|
||||
//! the load factor), for the vanilla collections whose order commands show:
|
||||
//! the scoreboard's objectives and teams.
|
||||
//! the load factor) and `java.util.HashSet<String>` (chained buckets split on
|
||||
//! resize). Commands list, and `scoreboard.dat` saves, in these orders.
|
||||
|
||||
/// The keys of an open hash map in their table slots.
|
||||
/// The keys of a fastutil open hash map in their table slots.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OpenOrder {
|
||||
keys: Vec<Option<String>>,
|
||||
@@ -18,7 +19,7 @@ impl Default for OpenOrder {
|
||||
}
|
||||
}
|
||||
/// `String.hashCode`.
|
||||
fn java_hash(s: &str) -> i32 {
|
||||
pub fn java_hash(s: &str) -> i32 {
|
||||
s.encode_utf16()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
|
||||
}
|
||||
@@ -32,6 +33,10 @@ fn array_size(expected: usize, f: f32) -> usize {
|
||||
let wanted = (expected as f64 / f64::from(f)).ceil() as usize;
|
||||
wanted.max(2).next_power_of_two()
|
||||
}
|
||||
/// `HashCommon.maxFill`.
|
||||
fn max_fill(n: usize, f: f32) -> usize {
|
||||
((n as f64 * f64::from(f)).ceil() as usize).min(n - 1)
|
||||
}
|
||||
impl OpenOrder {
|
||||
pub fn new(expected: usize, load: f32) -> Self {
|
||||
let n = array_size(expected, load);
|
||||
@@ -42,33 +47,52 @@ impl OpenOrder {
|
||||
load,
|
||||
}
|
||||
}
|
||||
fn max_fill(&self) -> usize {
|
||||
((self.keys.len() as f64 * f64::from(self.load)).ceil() as usize).min(self.keys.len() - 1)
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
fn slot(&self, key: &str) -> usize {
|
||||
mix(java_hash(key)) & (self.keys.len() - 1)
|
||||
}
|
||||
pub fn insert(&mut self, key: &str) {
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `put`: false when the key was already there.
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return false;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key.to_owned());
|
||||
// `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`.
|
||||
let old = self.size;
|
||||
self.size += 1;
|
||||
if self.size >= self.max_fill() {
|
||||
if old >= max_fill(self.keys.len(), self.load) {
|
||||
self.rehash(array_size(self.size + 1, self.load));
|
||||
}
|
||||
true
|
||||
}
|
||||
pub fn remove(&mut self, key: &str) {
|
||||
/// `remove`: false when the key was not there.
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
loop {
|
||||
match &self.keys[pos] {
|
||||
None => return,
|
||||
None => return false,
|
||||
Some(k) if k == key => break,
|
||||
Some(_) => pos = (pos + 1) & mask,
|
||||
}
|
||||
@@ -76,9 +100,10 @@ impl OpenOrder {
|
||||
self.size -= 1;
|
||||
self.shift_keys(pos);
|
||||
let n = self.keys.len();
|
||||
if n > self.min_n && self.size < self.max_fill() / 4 && n > 16 {
|
||||
if n > self.min_n && self.size < max_fill(n, self.load) / 4 && n > 16 {
|
||||
self.rehash(n / 2);
|
||||
}
|
||||
true
|
||||
}
|
||||
fn shift_keys(&mut self, mut pos: usize) {
|
||||
let mask = self.keys.len() - 1;
|
||||
@@ -107,6 +132,7 @@ impl OpenOrder {
|
||||
fn rehash(&mut self, new_n: usize) {
|
||||
let old = std::mem::replace(&mut self.keys, vec![None; new_n]);
|
||||
let mask = new_n - 1;
|
||||
// `for (int j = realSize(); j-- != 0;) { while (key[--i] == null); ... }`
|
||||
for key in old.into_iter().rev().flatten() {
|
||||
let mut pos = mix(java_hash(&key)) & mask;
|
||||
while self.keys[pos].is_some() {
|
||||
@@ -115,10 +141,84 @@ impl OpenOrder {
|
||||
self.keys[pos] = Some(key);
|
||||
}
|
||||
}
|
||||
/// The iteration order (`keySet().iterator()`: from the last slot down).
|
||||
pub fn keys(&self) -> impl Iterator<Item = &str> {
|
||||
/// `iterator()` and `forEach`: from the last slot down.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().rev().flatten().map(String::as_str)
|
||||
}
|
||||
/// `spliterator()` (what `stream()` uses): from the first slot up.
|
||||
pub fn stream(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().flatten().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys of a `java.util.HashSet<String>` in their buckets.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HashSetOrder {
|
||||
/// Empty until the first insertion (`HashMap.resize` on first `put`).
|
||||
table: Vec<Vec<String>>,
|
||||
size: usize,
|
||||
}
|
||||
/// `HashMap.hash`.
|
||||
fn spread(s: &str) -> usize {
|
||||
let h = java_hash(s) as u32;
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
impl HashSetOrder {
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
self.table[i].iter().any(|k| k == key)
|
||||
}
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
self.table = vec![Vec::new(); 16];
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
if self.table[i].iter().any(|k| k == key) {
|
||||
return false;
|
||||
}
|
||||
self.table[i].push(key.to_owned());
|
||||
self.size += 1;
|
||||
if self.size > self.table.len() * 3 / 4 {
|
||||
self.resize();
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Doubles the table; each bucket splits into its low and high halves in order.
|
||||
fn resize(&mut self) {
|
||||
let old = std::mem::take(&mut self.table);
|
||||
let n = old.len() * 2;
|
||||
self.table = vec![Vec::new(); n];
|
||||
for bucket in old {
|
||||
for key in bucket {
|
||||
let i = spread(&key) & (n - 1);
|
||||
self.table[i].push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
let Some(at) = self.table[i].iter().position(|k| k == key) else {
|
||||
return false;
|
||||
};
|
||||
self.table[i].remove(at);
|
||||
self.size -= 1;
|
||||
true
|
||||
}
|
||||
pub fn iter(&self) -> impl Iterator<Item = &String> {
|
||||
self.table.iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -127,27 +227,44 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hash_and_order() {
|
||||
assert_eq!(
|
||||
java_hash("harness"),
|
||||
assert_eq!(java_hash("harness"), {
|
||||
"harness"
|
||||
.chars()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))
|
||||
);
|
||||
});
|
||||
let mut o = OpenOrder::new(16, 0.5);
|
||||
for k in ["harness", "harness_h"] {
|
||||
o.insert(k);
|
||||
}
|
||||
let keys: Vec<&str> = o.keys().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert_eq!(o.iter().count(), 2);
|
||||
let mut asc: Vec<&str> = o.stream().collect();
|
||||
asc.reverse();
|
||||
assert_eq!(asc, o.iter().collect::<Vec<_>>());
|
||||
o.remove("harness");
|
||||
assert_eq!(o.keys().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
for i in 0..40 {
|
||||
o.insert(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.keys().count(), 41);
|
||||
assert_eq!(o.iter().count(), 41);
|
||||
for i in 0..40 {
|
||||
o.remove(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.keys().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_set_buckets() {
|
||||
let mut s = HashSetOrder::default();
|
||||
for i in 0..30 {
|
||||
assert!(s.insert(&format!("p{i}")));
|
||||
}
|
||||
assert!(!s.insert("p3"));
|
||||
assert_eq!(s.len(), 30);
|
||||
assert!(s.remove("p3") && !s.contains("p3"));
|
||||
// "Aa" and "BB" share a hash: insertion order within the bucket.
|
||||
let mut t = HashSetOrder::default();
|
||||
t.insert("BB");
|
||||
t.insert("Aa");
|
||||
assert_eq!(t.iter().collect::<Vec<_>>(), vec!["BB", "Aa"]);
|
||||
}
|
||||
}
|
||||
|
||||
+565
-332
File diff suppressed because it is too large
Load Diff
@@ -10,7 +10,7 @@ use horizon_client::{
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||
collections::{BTreeMap, VecDeque},
|
||||
sync::Arc,
|
||||
time::Instant,
|
||||
};
|
||||
@@ -46,7 +46,6 @@ pub(super) struct AdvState {
|
||||
pub(super) tree: Arc<Tree>,
|
||||
pub(super) progress: Progress,
|
||||
loaded: bool,
|
||||
pub(super) recipes: BTreeSet<String>,
|
||||
pub(super) toasts: VecDeque<Toast>,
|
||||
/// Awards skip the toast (`/advancement grant ... everything`).
|
||||
pub(super) quiet: bool,
|
||||
@@ -220,13 +219,9 @@ impl Game<'_> {
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.map(|v| Progress::from_json(&v))
|
||||
.unwrap_or_default();
|
||||
// Unlocked recipes come from the done recipe advancements' rewards.
|
||||
// The known recipes are the player's own (`recipeBook`), not the
|
||||
// rewards of done advancements: /recipe take sticks.
|
||||
let tree = self.adv.tree.clone();
|
||||
for a in &tree.list {
|
||||
if progress.done(a) {
|
||||
self.adv.recipes.extend(a.rewards.recipes.iter().cloned());
|
||||
}
|
||||
}
|
||||
self.adv.progress = progress;
|
||||
self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect();
|
||||
}
|
||||
@@ -381,6 +376,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// After `ServerRecipeBook.addRecipes`: the toast and the
|
||||
/// `recipe_unlocked` trigger of each recipe now known.
|
||||
pub(super) fn recipe_unlocked(&mut self, unlocked: &[String]) {
|
||||
self.recipe_toast(unlocked);
|
||||
for r in unlocked {
|
||||
let r = r.clone();
|
||||
self.trigger("minecraft:recipe_unlocked", move |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
});
|
||||
}
|
||||
}
|
||||
/// `PlayerAdvancements.award` once done: rewards, toast, announcement.
|
||||
fn award(&mut self, index: usize) {
|
||||
let tree = self.adv.tree.clone();
|
||||
@@ -389,12 +395,18 @@ impl Game<'_> {
|
||||
if a.rewards.experience > 0 {
|
||||
self.experience.give(a.rewards.experience);
|
||||
}
|
||||
let mut unlocked = Vec::new();
|
||||
for r in &a.rewards.recipes {
|
||||
if self.adv.recipes.insert(r.clone()) {
|
||||
unlocked.push(r.clone());
|
||||
}
|
||||
}
|
||||
// ServerPlayer.awardRecipesByKey: the rewards that name a recipe.
|
||||
let rewards: Vec<String> = a
|
||||
.rewards
|
||||
.recipes
|
||||
.iter()
|
||||
.filter(|r| self.res.stations.recipe_index.contains(r))
|
||||
.cloned()
|
||||
.collect();
|
||||
let (_, unlocked) = self
|
||||
.level
|
||||
.recipe_book
|
||||
.add_recipes(&self.res.stations.recipe_index, &rewards);
|
||||
for table in &a.rewards.loot {
|
||||
let items = self
|
||||
.res
|
||||
@@ -431,12 +443,7 @@ impl Game<'_> {
|
||||
));
|
||||
}
|
||||
}
|
||||
self.recipe_toast(&unlocked);
|
||||
for r in unlocked {
|
||||
self.trigger("minecraft:recipe_unlocked", |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
});
|
||||
}
|
||||
self.recipe_unlocked(&unlocked);
|
||||
}
|
||||
/// `InventoryChangeTrigger`, checked when the inventory changes.
|
||||
pub(super) fn check_inventory_trigger(&mut self) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
banner::{self, BannerLayer},
|
||||
containers::{Banner, BlockEntity},
|
||||
containers::BlockEntity,
|
||||
items::ItemStack,
|
||||
};
|
||||
|
||||
@@ -19,7 +19,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// A placed banner takes the item's layers and name.
|
||||
pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) {
|
||||
self.pending_banner.remove(&pos);
|
||||
self.pending.banner.remove(&pos);
|
||||
if !stack.item.ends_with("_banner") {
|
||||
return;
|
||||
}
|
||||
@@ -30,20 +30,6 @@ impl Game<'_> {
|
||||
b.name = stack.custom_name().map(str::to_owned);
|
||||
}
|
||||
}
|
||||
/// The layers a banner dropped at `pos` carries.
|
||||
pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if !stack.item.ends_with("_banner") {
|
||||
return;
|
||||
}
|
||||
if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) {
|
||||
let data = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
if name.is_some() {
|
||||
data.custom_name = name;
|
||||
}
|
||||
stack.tidy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture names and tints of banner layers (`Sheets.getBannerSprite`).
|
||||
|
||||
@@ -282,6 +282,13 @@ impl Game<'_> {
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
// The mob effect registry: every effect `/effect` and the
|
||||
// `mob_effect` resource arguments accept.
|
||||
reg.effects = horizon_client::brewing::EFFECTS
|
||||
.iter()
|
||||
.map(|e| format!("minecraft:{}", e.id))
|
||||
.collect();
|
||||
reg.effects.sort();
|
||||
reg.enchantments = list("data/minecraft/enchantment");
|
||||
reg.structures = list("data/minecraft/worldgen/structure");
|
||||
reg.biomes = list("data/minecraft/worldgen/biome");
|
||||
@@ -668,17 +675,21 @@ impl Game<'_> {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let below_world = p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64);
|
||||
let name = self.player_display_text();
|
||||
let message = match cause {
|
||||
Some(key) => Text::translate(&key, &[Text::literal(PLAYER_NAME)]),
|
||||
None if p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64) => {
|
||||
Text::translate("death.attack.outOfWorld", &[Text::literal(PLAYER_NAME)])
|
||||
}
|
||||
Some(key) => Text::translate(&key, &[name]),
|
||||
None if below_world => Text::translate("death.attack.outOfWorld", &[name]),
|
||||
None => self.combat_death_message(),
|
||||
};
|
||||
self.ui.death_text = Some(message.clone());
|
||||
self.system_message(message);
|
||||
// ServerPlayer.die: a team that hides death messages keeps it out of
|
||||
// the dying player's own chat (the death screen still shows it).
|
||||
if horizon_client::scoreboard::own_death_message_shown(self.player_team()) {
|
||||
self.system_message(message);
|
||||
}
|
||||
}
|
||||
/// F1 hides the HUD (and hand); the screenshot key still works.
|
||||
/// F1 hides the HUD (see `hud`); the screenshot key still works.
|
||||
pub(super) fn toggle_hide_gui(&mut self) {
|
||||
self.ui.hide_gui = !self.ui.hide_gui;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ pub(super) struct CombatTracker {
|
||||
pub(super) last_hurt_mob: Option<(u32, i64)>,
|
||||
/// The mob whose projectile is hitting the player now.
|
||||
pub(super) projectile_owner: Option<u32>,
|
||||
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
|
||||
/// fire decides whom the blast may hurt.
|
||||
pub(super) explosion_source: Option<u32>,
|
||||
/// The player's fall distance before this tick's movement (as of the
|
||||
/// end of the last one).
|
||||
fall_before: f64,
|
||||
|
||||
@@ -1477,13 +1477,12 @@ impl Game<'_> {
|
||||
self.res.facts.get(previous).name.clone(),
|
||||
self.res.facts.get(state).name.clone(),
|
||||
);
|
||||
// The command clears the old block entity without its side effects
|
||||
// (UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS); the new block gets a fresh one.
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if old != new {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
self.jukebox_removed(pos);
|
||||
self.world.block_entities.remove(&key);
|
||||
if let Some(entity) = horizon_client::containers::BlockEntity::for_block(&new) {
|
||||
self.world.block_entities.insert(key, entity);
|
||||
}
|
||||
}
|
||||
if strict {
|
||||
self.with_level(|b, level, ticks| {
|
||||
@@ -1502,6 +1501,12 @@ impl Game<'_> {
|
||||
self.level_set(pos, state)
|
||||
.map_err(|e| CommandError::new(Text::literal(e.to_string())))?;
|
||||
}
|
||||
if old != new
|
||||
&& self.world.block(pos[0], pos[1], pos[2]) == state
|
||||
&& let Some(entity) = horizon_client::containers::BlockEntity::for_block(&new)
|
||||
{
|
||||
self.world.block_entities.insert(key, entity);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn cmd_setblock(&mut self, ctx: &Context) -> R<i32> {
|
||||
@@ -1531,31 +1536,14 @@ impl Game<'_> {
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
/// `Level.destroyBlock(pos, true)`: the block's drops without a tool or
|
||||
/// breaker (its loot table, contents of a container), then air.
|
||||
/// `Level.destroyBlock(pos, true)` through the behaviour library: the
|
||||
/// destroy event, the block's drops without a tool or breaker, then its
|
||||
/// fluid's block, the block entity spilling its contents on the way.
|
||||
pub(super) fn destroy_block_dropping(&mut self, pos: [i32; 3]) -> R<()> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
self.destroy_particles(pos, state);
|
||||
self.jukebox_removed(pos);
|
||||
if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) {
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
self.release_contents(pos, entity, &name);
|
||||
}
|
||||
let drops = self.res.items.block_drops_in(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
None,
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
);
|
||||
for d in drops {
|
||||
if &*d.item != "minecraft:air" {
|
||||
self.pop_resource(pos, d);
|
||||
}
|
||||
}
|
||||
let air = self.world.air;
|
||||
self.place_state(pos, air, false)?;
|
||||
Ok(())
|
||||
let at = horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
self.with_level(|b, level, ticks| b.destroy_block(level, ticks, at, true));
|
||||
self.process_level_events()
|
||||
.map_err(|e| CommandError::new(Text::literal(e.to_string())))
|
||||
}
|
||||
/// The block entity part of `BlockInput.place`: load the block entity
|
||||
/// from the argument's tag; true when its saved data changed.
|
||||
|
||||
@@ -345,7 +345,7 @@ impl Game<'_> {
|
||||
.position_arg(ctx, "pos")
|
||||
.unwrap_or_else(|| self.source_position());
|
||||
let (x, z) = (p[0], p[2]);
|
||||
if self.border.center == [x, z] {
|
||||
if self.border.center() == [x, z] {
|
||||
return Err(err("commands.worldborder.center.failed", &[]));
|
||||
}
|
||||
if x.abs() > 2.999_998_4e7 || z.abs() > 2.999_998_4e7 {
|
||||
@@ -354,7 +354,7 @@ impl Game<'_> {
|
||||
&[&"2.9999984E7"],
|
||||
));
|
||||
}
|
||||
self.border.center = [x, z];
|
||||
self.border.set_center([x, z]);
|
||||
self.feedback(Text::translate(
|
||||
"commands.worldborder.center.success",
|
||||
&[Text::literal(float2(x)), Text::literal(float2(z))],
|
||||
|
||||
@@ -30,66 +30,9 @@ fn java_double_text(v: f64) -> Text {
|
||||
impl Game<'_> {
|
||||
// ---- /recipe -----------------------------------------------------------
|
||||
|
||||
/// Every `minecraft:` recipe that `/recipe` can give (non-special ones).
|
||||
/// `Recipe.display().size()`.
|
||||
fn recipe_display_count(&self, id: &str) -> i32 {
|
||||
let path = self.options.resources.join(format!(
|
||||
"data/minecraft/recipe/{}.json",
|
||||
id.trim_start_matches("minecraft:")
|
||||
));
|
||||
let Some(v) = std::fs::read(path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
else {
|
||||
return 1;
|
||||
};
|
||||
if v["type"].as_str() != Some("minecraft:crafting_transmute") {
|
||||
return 1;
|
||||
}
|
||||
// TransmuteRecipe: material_count defaults to exactly 1; open
|
||||
// bounds are 1 and 8.
|
||||
let (min, max) = match &v["material_count"] {
|
||||
serde_json::Value::Null => (1, 1),
|
||||
serde_json::Value::Number(n) => {
|
||||
let n = n.as_i64().unwrap_or(1);
|
||||
(n, n)
|
||||
}
|
||||
b => (
|
||||
b["min"].as_i64().unwrap_or(1),
|
||||
b["max"].as_i64().unwrap_or(8),
|
||||
),
|
||||
};
|
||||
(max - min + 1).max(0) as i32
|
||||
}
|
||||
/// Every recipe id of the recipe manager (what `/recipe` resolves and suggests).
|
||||
pub(super) fn learnable_recipes(&self) -> Vec<String> {
|
||||
// RecipeManager's learnable (non-special) recipes, as exported.
|
||||
if !self.ui.registries.learnable_recipes.is_empty() {
|
||||
return self.ui.registries.learnable_recipes.clone();
|
||||
}
|
||||
let dir = self.options.resources.join("data/minecraft/recipe");
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return out;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if path.extension().and_then(|x| x.to_str()) != Some("json") {
|
||||
continue;
|
||||
}
|
||||
let special = std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
.and_then(|v| v["type"].as_str().map(|t| t.contains("crafting_special_")))
|
||||
.unwrap_or(false);
|
||||
if !special {
|
||||
out.push(format!("minecraft:{stem}"));
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
self.res.stations.recipe_index.ids().cloned().collect()
|
||||
}
|
||||
pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "targets", true)?;
|
||||
@@ -109,25 +52,15 @@ impl Game<'_> {
|
||||
// ServerRecipeBook.addRecipes/removeRecipes count recipe book
|
||||
// displays (a transmute recipe has one per material count).
|
||||
let mut n = 0;
|
||||
let mut unlocked = Vec::new();
|
||||
for r in &recipes {
|
||||
let changed = if give {
|
||||
self.adv.recipes.insert(r.clone())
|
||||
} else {
|
||||
self.adv.recipes.remove(r)
|
||||
};
|
||||
if changed {
|
||||
n += self.recipe_display_count(r);
|
||||
if give {
|
||||
unlocked.push(r.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in unlocked {
|
||||
self.trigger("minecraft:recipe_unlocked", |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
});
|
||||
}
|
||||
// ServerPlayer.awardRecipes / resetRecipes: the displays changed.
|
||||
let index = &self.res.stations.recipe_index;
|
||||
n += if give {
|
||||
let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes);
|
||||
self.recipe_unlocked(&unlocked);
|
||||
count as i32
|
||||
} else {
|
||||
self.level.recipe_book.remove_recipes(index, &recipes) as i32
|
||||
};
|
||||
tracker.track(&h, n);
|
||||
}
|
||||
let verb = if give { "give" } else { "take" };
|
||||
|
||||
@@ -102,7 +102,7 @@ impl Game<'_> {
|
||||
m.extra.scratch[3] -= 1;
|
||||
}
|
||||
// The visited positions fade after 6000 ticks.
|
||||
if m.extra.ints[2] > 0 && m.age >= m.extra.ints[2] {
|
||||
if m.extra.ints[2] > 0 && m.age as i32 >= m.extra.ints[2] {
|
||||
m.extra.positions.clear();
|
||||
m.extra.ints[2] = 0;
|
||||
}
|
||||
@@ -141,9 +141,11 @@ impl Game<'_> {
|
||||
if next == -2 {
|
||||
return false;
|
||||
}
|
||||
let interval = |m: &mut Mob| 504_000 + i64::from(m.random.next_int_bound(48_001).unwrap_or(0));
|
||||
// updateWeathering draws from the level random.
|
||||
let r = &mut self.world.random;
|
||||
let mut interval = || 504_000 + i64::from(r.next_int_bound(48_001).unwrap_or(0));
|
||||
if next == -1 {
|
||||
m.extra.vector[0] = (now + interval(m)) as f64;
|
||||
m.extra.vector[0] = (now + interval()) as f64;
|
||||
return false;
|
||||
}
|
||||
let fully = m.extra.variant >= 3;
|
||||
@@ -153,7 +155,7 @@ impl Game<'_> {
|
||||
m.extra.vector[0] = if new >= 3 {
|
||||
0.0
|
||||
} else {
|
||||
(next + interval(m)) as f64
|
||||
(next + interval()) as f64
|
||||
};
|
||||
}
|
||||
if fully && self.golem_can_turn_to_statue(m) {
|
||||
@@ -177,8 +179,9 @@ impl Game<'_> {
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
// The pose comes from the golem's own random (`this.random.nextInt(0, 4)`).
|
||||
let pose = ["standing", "sitting", "running", "star"]
|
||||
[self.world.random.next_int_bound(4).unwrap_or(0) as usize];
|
||||
[m.random.next_int_bound(4).unwrap_or(0) as usize];
|
||||
// Direction.fromYRot.
|
||||
let facing = ["south", "west", "north", "east"]
|
||||
[((f64::from(m.yaw) / 90.0 + 0.5).floor() as i32 & 3) as usize];
|
||||
@@ -186,7 +189,7 @@ impl Game<'_> {
|
||||
name: "minecraft:oxidized_copper_golem_statue".into(),
|
||||
properties: [
|
||||
("facing".to_string(), facing.to_string()),
|
||||
("pose".to_string(), pose.to_string()),
|
||||
("copper_golem_pose".to_string(), pose.to_string()),
|
||||
("waterlogged".to_string(), "false".to_string()),
|
||||
]
|
||||
.into(),
|
||||
@@ -212,15 +215,18 @@ impl Game<'_> {
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
/// `dropPreservedEquipment`: the carried stack and the antenna.
|
||||
/// `Mob.dropPreservedEquipment`: the guaranteed drops in `EquipmentSlot`
|
||||
/// order, the carried stack (main hand) then the antenna flower (saddle),
|
||||
/// each `spawnAtLocation` at the golem's feet.
|
||||
pub(super) fn golem_drop_equipment(&mut self, m: &mut Mob) {
|
||||
let at = [m.position.x, m.position.y + 0.5, m.position.z];
|
||||
let at = m.position;
|
||||
if let Some(stack) = held(m).cloned() {
|
||||
set_held(m, None);
|
||||
self.spawn_item(stack, at, [0.0, 0.2, 0.0], 10);
|
||||
self.spawn_at_location(at, 0.0, stack);
|
||||
}
|
||||
if let Some(antenna) = m.extra.legs.take() {
|
||||
self.spawn_item(ItemStack::new(&antenna, 1), at, [0.0, 0.2, 0.0], 10);
|
||||
if let Some(antenna) = m.saddle_item() {
|
||||
m.set_saddle(None);
|
||||
self.spawn_at_location(at, 0.0, antenna);
|
||||
}
|
||||
}
|
||||
// ---- containers -------------------------------------------------------
|
||||
@@ -252,7 +258,8 @@ impl Game<'_> {
|
||||
fn golem_chest_blocked(&self, keys: &[Key]) -> bool {
|
||||
keys.iter().any(|k| {
|
||||
let above = self.world.block(k.0, k.1 + 1, k.2);
|
||||
self.behaviours.facts(above).flags & horizon_world::level::data::state_flags::CONDUCTOR
|
||||
self.res.behaviours.facts(above).flags
|
||||
& horizon_world::level::data::state_flags::CONDUCTOR
|
||||
!= 0
|
||||
})
|
||||
}
|
||||
@@ -273,7 +280,11 @@ impl Game<'_> {
|
||||
None
|
||||
}
|
||||
fn golem_max_stack(&self, stack: &ItemStack) -> u32 {
|
||||
self.res.items.get(&stack.item).map_or(64, |i| i.max_stack).max(1)
|
||||
self.res
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.map_or(64, |i| i.max_stack)
|
||||
.max(1)
|
||||
}
|
||||
/// `pickupItemFromContainer`: up to 16 of the first non-empty slot.
|
||||
fn golem_pick_up(&mut self, keys: &[Key]) -> Option<ItemStack> {
|
||||
@@ -362,7 +373,10 @@ impl Game<'_> {
|
||||
let Some(h) = m.extra.home else { return false };
|
||||
let key = (h[0], h[1], h[2]);
|
||||
let valid = self.golem_wanted_block(m, key)
|
||||
&& matches!(self.world.block_entities.get(&key), Some(BlockEntity::Chest(_)))
|
||||
&& matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Chest(_))
|
||||
)
|
||||
&& !self.golem_chest_blocked(&self.golem_container(key));
|
||||
if !valid {
|
||||
return false;
|
||||
@@ -389,7 +403,11 @@ impl Game<'_> {
|
||||
f64::from(n.y) + m.kind.height / 2.0,
|
||||
f64::from(n.z) + 0.5,
|
||||
],
|
||||
None => [m.position.x, m.position.y + m.kind.height / 2.0, m.position.z],
|
||||
None => [
|
||||
m.position.x,
|
||||
m.position.y + m.kind.height / 2.0,
|
||||
m.position.z,
|
||||
],
|
||||
};
|
||||
let reach = golem_within(m, self.golem_range(m), from, h);
|
||||
(path.is_none() && !reach) || reach
|
||||
@@ -446,7 +464,7 @@ impl Game<'_> {
|
||||
}
|
||||
m.extra.positions.retain(|p| p[1] >= UNREACHABLE);
|
||||
m.extra.positions.extend(list);
|
||||
m.extra.ints[2] = m.age + MEMORY_TICKS;
|
||||
m.extra.ints[2] = m.age as i32 + MEMORY_TICKS;
|
||||
}
|
||||
fn golem_mark_unreachable(&mut self, m: &mut Mob, h: [i32; 3]) {
|
||||
m.extra.positions.retain(|p| *p != h);
|
||||
@@ -454,11 +472,16 @@ impl Game<'_> {
|
||||
if !m.extra.positions.contains(&marked) {
|
||||
m.extra.positions.push(marked);
|
||||
}
|
||||
let count = m.extra.positions.iter().filter(|p| p[1] >= UNREACHABLE).count();
|
||||
let count = m
|
||||
.extra
|
||||
.positions
|
||||
.iter()
|
||||
.filter(|p| p[1] >= UNREACHABLE)
|
||||
.count();
|
||||
if count > 50 {
|
||||
self.golem_enter_cooldown(m);
|
||||
} else {
|
||||
m.extra.ints[2] = m.age + MEMORY_TICKS;
|
||||
m.extra.ints[2] = m.age as i32 + MEMORY_TICKS;
|
||||
}
|
||||
}
|
||||
fn golem_stop_targeting(&mut self, m: &mut Mob) {
|
||||
@@ -495,7 +518,9 @@ impl Game<'_> {
|
||||
}
|
||||
fn golem_chest_sound(&mut self, key: Key, open: bool) {
|
||||
let name = self.golem_block_name(key);
|
||||
let base = name.trim_start_matches("minecraft:").trim_start_matches("waxed_");
|
||||
let base = name
|
||||
.trim_start_matches("minecraft:")
|
||||
.trim_start_matches("waxed_");
|
||||
let kind = if base.starts_with("weathered") {
|
||||
"copper_chest_weathered"
|
||||
} else if base.starts_with("oxidized") {
|
||||
@@ -508,8 +533,12 @@ impl Game<'_> {
|
||||
let side = if open { "open" } else { "close" };
|
||||
let at = chest_center([key.0, key.1, key.2]);
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio
|
||||
.play(&format!("minecraft:block.{kind}.{side}"), Some(at), 0.5, pitch);
|
||||
self.audio.play(
|
||||
&format!("minecraft:block.{kind}.{side}"),
|
||||
Some(at),
|
||||
0.5,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
fn golem_on_queuing(&mut self, m: &mut Mob) {
|
||||
let Some(h) = m.extra.home else { return };
|
||||
@@ -601,7 +630,8 @@ impl Game<'_> {
|
||||
&& let Some(sound) = sound
|
||||
{
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
self.audio.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
|
||||
self.audio
|
||||
.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
|
||||
}
|
||||
if ticks == 60 {
|
||||
self.golem_release(m);
|
||||
@@ -626,7 +656,9 @@ impl Game<'_> {
|
||||
.any(|s| held(m).is_some_and(|h| h.item == s.item))
|
||||
{
|
||||
// putDownItem.
|
||||
let stack = held(m).cloned().unwrap_or_else(|| ItemStack::new("minecraft:air", 0));
|
||||
let stack = held(m)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| ItemStack::new("minecraft:air", 0));
|
||||
let left = self.golem_put_down(&keys, stack);
|
||||
let emptied = left.is_none();
|
||||
set_held(m, left);
|
||||
@@ -657,25 +689,39 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
set_held(&mut self.mobs[index], None);
|
||||
// BehaviorUtils.throwItem: from 0.3 below the golem's eyes towards
|
||||
// the player's feet at 0.3 blocks a tick, default pickup delay.
|
||||
let p = self.player.as_ref().map(|p| p.position);
|
||||
let from = [at[0], at[1] + 0.9, at[2]];
|
||||
let eye = self.mobs[index].eye_height();
|
||||
let from = [at[0], at[1] + eye - f64::from(0.3f32), at[2]];
|
||||
let v = p.map_or([0.0; 3], |p| {
|
||||
let d = [p.x - from[0], p.y + 1.0 - from[1], p.z - from[2]];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
|
||||
[d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]
|
||||
let d = [p.x - at[0], p.y - at[1], p.z - at[2]];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
if len < 1.0e-5 {
|
||||
return [0.0; 3];
|
||||
}
|
||||
let k = f64::from(0.3f32);
|
||||
[d[0] / len * k, d[1] / len * k, d[2] / len * k]
|
||||
});
|
||||
self.spawn_item(h, from, v, 40);
|
||||
self.spawn_item(h, from, v, 10);
|
||||
return true;
|
||||
}
|
||||
let name = item;
|
||||
let is_axe = name.ends_with("_axe");
|
||||
let waxed = self.mobs[index].extra.vector[0] as i64 == -2;
|
||||
if name == "minecraft:shears" && self.golem_shearable(index) {
|
||||
let antenna = self.mobs[index].extra.legs.take();
|
||||
// CopperGolem.shear: the sound, the antenna slot emptied (an
|
||||
// unequip) and the flower dropped 1.5 up.
|
||||
self.audio
|
||||
.play("minecraft:entity.copper_golem.shear", Some(at), 1.0, 1.0);
|
||||
let antenna = self.mobs[index].saddle_item();
|
||||
self.mobs[index].set_saddle(None);
|
||||
let id = self.mobs[index].id;
|
||||
let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None);
|
||||
self.post_game_event("minecraft:unequip", at, ctx);
|
||||
if let Some(a) = antenna {
|
||||
self.spawn_item(ItemStack::new(&a, 1), [at[0], at[1] + 1.5, at[2]], [0.0, 0.2, 0.0], 10);
|
||||
let p = self.mobs[index].position;
|
||||
self.spawn_at_location(p, 1.5, a);
|
||||
}
|
||||
self.damage_held_tool();
|
||||
return true;
|
||||
@@ -705,13 +751,14 @@ impl Game<'_> {
|
||||
}
|
||||
false
|
||||
}
|
||||
fn golem_shearable(&self, index: usize) -> bool {
|
||||
self.mobs[index].extra.legs.as_deref().is_some_and(|a| {
|
||||
/// `readyForShearing`: the antenna holds a flower shears take.
|
||||
pub(super) fn golem_shearable(&self, index: usize) -> bool {
|
||||
self.mobs[index].saddle_item().is_some_and(|a| {
|
||||
self.res
|
||||
.items
|
||||
.item_tags
|
||||
.get("minecraft:shearable_from_copper_golem")
|
||||
.is_some_and(|t| t.contains(a))
|
||||
.is_some_and(|t| t.contains(&*a.item))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,29 @@
|
||||
//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an
|
||||
//! awake heart in a pale oak trunk spawns a creaking that protects it,
|
||||
//! hurting the creaking makes the heart emit trails and spread resin over
|
||||
//! the logs, and breaking the heart tears the creaking down.
|
||||
use super::Game;
|
||||
//! The creaking heart block entity in the game: `mobs::creaking_heart`
|
||||
//! ticks each heart (spawning, letting go of and bleeding for its creaking)
|
||||
//! and this applies what it reports to the world, the mobs and the speakers.
|
||||
use super::{Game, creatures::seen};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
containers::{BlockEntity, CreakingHeart},
|
||||
mobs::creaking,
|
||||
mobs::{
|
||||
Mob, MobType,
|
||||
creaking_heart::{self, HeartEvent, HeartHost},
|
||||
},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
position::BlockPos,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
type Pos = (i32, i32, i32);
|
||||
|
||||
/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`.
|
||||
const ORANGE: u32 = 16_545_810;
|
||||
const GRAY: u32 = 6_250_335;
|
||||
/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`.
|
||||
const TOO_FAR: f64 = 34.0;
|
||||
|
||||
/// `Direction.values()`: down, up, north, south, west, east.
|
||||
const DIRECTIONS: [[i32; 3]; 6] = [
|
||||
[0, -1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, -1],
|
||||
[0, 0, 1],
|
||||
[-1, 0, 0],
|
||||
[1, 0, 0],
|
||||
];
|
||||
const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
|
||||
|
||||
/// Comparator input of a heart (`getAnalogOutputSignal`).
|
||||
pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option<i32> {
|
||||
match world.block_entities.get(&(pos.x, pos.y, pos.z))? {
|
||||
@@ -40,6 +32,59 @@ pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos)
|
||||
}
|
||||
}
|
||||
|
||||
/// The game's mobs as a heart sees them, taken out of the game for the tick.
|
||||
struct Host<'a> {
|
||||
mobs: &'a mut Vec<Mob>,
|
||||
added: Vec<Mob>,
|
||||
uuids: &'a mut HashMap<u32, [i32; 4]>,
|
||||
creaking: Option<Arc<MobType>>,
|
||||
next_entity: &'a mut u32,
|
||||
spawning: bool,
|
||||
}
|
||||
impl HeartHost for Host<'_> {
|
||||
fn mob(&self, id: u32) -> Option<&Mob> {
|
||||
self.mobs
|
||||
.iter()
|
||||
.chain(self.added.iter())
|
||||
.find(|m| m.id == id && !m.removed)
|
||||
}
|
||||
fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> {
|
||||
self.mobs
|
||||
.iter_mut()
|
||||
.chain(self.added.iter_mut())
|
||||
.find(|m| m.id == id && !m.removed)
|
||||
}
|
||||
fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
|
||||
self.uuids
|
||||
.iter()
|
||||
.find(|(id, u)| **u == uuid && self.mob(**id).is_some())
|
||||
.map(|(id, _)| *id)
|
||||
}
|
||||
fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
||||
*self
|
||||
.uuids
|
||||
.entry(id)
|
||||
.or_insert_with(horizon_client::save::random_uuid)
|
||||
}
|
||||
fn creaking_type(&self) -> Option<Arc<MobType>> {
|
||||
self.creaking.clone()
|
||||
}
|
||||
fn create_mob(&mut self, kind: Arc<MobType>, at: Vec3) -> Mob {
|
||||
*self.next_entity += 1;
|
||||
// A new entity's random is its own (Mob::new seeds it).
|
||||
let mut m = Mob::new(*self.next_entity, kind, at, 0.0);
|
||||
let seed = i64::from(m.id);
|
||||
horizon_client::mobs::monster_brain::init(&mut m, seed);
|
||||
m
|
||||
}
|
||||
fn add_mob(&mut self, m: Mob) {
|
||||
self.added.push(m);
|
||||
}
|
||||
fn spawning_monsters(&self) -> bool {
|
||||
self.spawning
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn heart_state_name(&self, state: BlockStateId) -> String {
|
||||
self.res
|
||||
@@ -49,204 +94,75 @@ impl Game<'_> {
|
||||
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
/// `Util.shuffledCopy(Direction.values(), random)`.
|
||||
fn shuffled_directions(&mut self) -> [usize; 6] {
|
||||
let mut order = [0, 1, 2, 3, 4, 5];
|
||||
for i in (2..=6).rev() {
|
||||
let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
|
||||
order.swap(i - 1, j);
|
||||
}
|
||||
order
|
||||
}
|
||||
fn is_pale_oak_log(&self, p: Pos) -> bool {
|
||||
let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name;
|
||||
self.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:pale_oak_logs")
|
||||
.is_some_and(|s| s.contains(&**name))
|
||||
}
|
||||
fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> {
|
||||
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
|
||||
Some((m.center(), m.bounds()))
|
||||
}
|
||||
/// The protector's entity, resolving a UUID read from a save.
|
||||
fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option<u32> {
|
||||
let (id, uuid) = heart.creaking?;
|
||||
if let Some(id) = id {
|
||||
if self.mobs.iter().any(|m| m.id == id && !m.removed) {
|
||||
return Some(id);
|
||||
}
|
||||
// The entity is gone: remember it by UUID until it reappears.
|
||||
heart.creaking = Some((None, uuid));
|
||||
}
|
||||
if let Some(id) = self.mob_id_for_uuid(uuid) {
|
||||
heart.creaking = Some((Some(id), uuid));
|
||||
return Some(id);
|
||||
}
|
||||
if heart.ticks_existed >= 30 {
|
||||
heart.creaking = None;
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart.
|
||||
fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) {
|
||||
let Some(id) = self.heart_protector(heart) else {
|
||||
return;
|
||||
/// Runs `f` on the heart at `key` with the game's mobs and level random,
|
||||
/// then applies what the heart reported.
|
||||
fn with_heart(
|
||||
&mut self,
|
||||
key: Pos,
|
||||
heart: &mut CreakingHeart,
|
||||
f: impl FnOnce(
|
||||
&mut CreakingHeart,
|
||||
&horizon_client::mobs::MobWorld,
|
||||
&mut LegacyRandom,
|
||||
&mut Host,
|
||||
&mut Vec<HeartEvent>,
|
||||
),
|
||||
) -> Result<()> {
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
let mut uuids = std::mem::take(&mut self.persist.uuids);
|
||||
let mut next_entity = self.next_entity;
|
||||
let mut random = self.world.random.clone();
|
||||
let spawning = self.spawning_monsters();
|
||||
let creaking = self.res.mob_types.get("minecraft:creaking").cloned();
|
||||
let player_uuid = self.level.player_uuid;
|
||||
let snapshot: Vec<_> = mobs.iter().map(|m| seen(m, player_uuid)).collect();
|
||||
let mut events = Vec::new();
|
||||
let added = {
|
||||
let w = self.mob_world_base(&snapshot);
|
||||
let mut host = Host {
|
||||
mobs: &mut mobs,
|
||||
added: Vec::new(),
|
||||
uuids: &mut uuids,
|
||||
creaking,
|
||||
next_entity: &mut next_entity,
|
||||
spawning,
|
||||
};
|
||||
f(heart, &w, &mut random, &mut host, &mut events);
|
||||
host.added
|
||||
};
|
||||
if by_player {
|
||||
// creakingDeathEffects: a twitching death.
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
creaking::set_tearing_down(m);
|
||||
m.health = 0.0;
|
||||
m.death_time = m.death_time.max(0);
|
||||
let at = m.center();
|
||||
self.audio
|
||||
.play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0);
|
||||
}
|
||||
} else if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
|
||||
let mut events = Vec::new();
|
||||
creaking::tear_down(&mut self.mobs[i], &mut events);
|
||||
let _ = self.handle_mob_events(events);
|
||||
}
|
||||
heart.creaking = None;
|
||||
}
|
||||
fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 {
|
||||
self.mob_center(id).map_or(0.0, |_| {
|
||||
let m = self.mobs.iter().find(|m| m.id == id).unwrap();
|
||||
let at = (
|
||||
f64::from(pos.0) + 0.5,
|
||||
f64::from(pos.1),
|
||||
f64::from(pos.2) + 0.5,
|
||||
);
|
||||
((m.position.x - at.0).powi(2)
|
||||
+ (m.position.y - at.1).powi(2)
|
||||
+ (m.position.z - at.2).powi(2))
|
||||
.sqrt()
|
||||
})
|
||||
}
|
||||
/// `emitParticles`: trails between the creaking and the heart.
|
||||
fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) {
|
||||
let Some(id) = self.heart_protector(heart) else {
|
||||
return;
|
||||
};
|
||||
let Some((_, b)) = self.mob_center(id) else {
|
||||
return;
|
||||
};
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
for _ in 0..count {
|
||||
let r = &mut self.world.random;
|
||||
let mut source = [
|
||||
lo.x + r.next_double() * (hi.x - lo.x),
|
||||
lo.y + r.next_double() * (hi.y - lo.y),
|
||||
lo.z + r.next_double() * (hi.z - lo.z),
|
||||
];
|
||||
let mut destination = [
|
||||
f64::from(pos.0) + r.next_double(),
|
||||
f64::from(pos.1) + r.next_double(),
|
||||
f64::from(pos.2) + r.next_double(),
|
||||
];
|
||||
if towards {
|
||||
std::mem::swap(&mut source, &mut destination);
|
||||
}
|
||||
let duration = r.next_int_bound(40).unwrap_or(0) + 10;
|
||||
let color = if towards { ORANGE } else { GRAY };
|
||||
self.particles.add(
|
||||
&ParticleOptions::trail(destination, color, duration),
|
||||
source,
|
||||
[0.0; 3],
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log
|
||||
/// face found within two steps of pale oak logs.
|
||||
fn heart_spread_resin(&mut self, pos: Pos) -> Option<Pos> {
|
||||
let mut visited: HashSet<Pos> = HashSet::new();
|
||||
let mut queue: VecDeque<(Pos, i32)> = VecDeque::new();
|
||||
queue.push_back((pos, 0));
|
||||
let mut count = 0;
|
||||
while let Some((current, depth)) = queue.pop_front() {
|
||||
if !visited.insert(current) {
|
||||
continue;
|
||||
}
|
||||
// The node processor.
|
||||
if self.is_pale_oak_log(current) {
|
||||
for d in self.shuffled_directions() {
|
||||
let n = (
|
||||
current.0 + DIRECTIONS[d][0],
|
||||
current.1 + DIRECTIONS[d][1],
|
||||
current.2 + DIRECTIONS[d][2],
|
||||
);
|
||||
let neighbour = self.world.block(n.0, n.1, n.2);
|
||||
let opposite = d ^ 1;
|
||||
let clump = self.resin_clump_for(neighbour);
|
||||
let Some(clump) = clump else { continue };
|
||||
if self.prop_is(clump, FACE_NAMES[opposite]) {
|
||||
continue;
|
||||
}
|
||||
let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else {
|
||||
continue;
|
||||
};
|
||||
let _ = self.level_set([n.0, n.1, n.2], placed);
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
count += 1;
|
||||
if count >= 64 {
|
||||
return None;
|
||||
}
|
||||
if depth < 2 {
|
||||
// The neighbour provider: adjacent pale oak logs.
|
||||
for d in self.shuffled_directions() {
|
||||
let n = (
|
||||
current.0 + DIRECTIONS[d][0],
|
||||
current.1 + DIRECTIONS[d][1],
|
||||
current.2 + DIRECTIONS[d][2],
|
||||
);
|
||||
if self.is_pale_oak_log(n) {
|
||||
queue.push_back((n, depth + 1));
|
||||
}
|
||||
mobs.extend(added);
|
||||
self.mobs = mobs;
|
||||
self.persist.uuids = uuids;
|
||||
self.next_entity = next_entity;
|
||||
self.world.random = random;
|
||||
let mut mob_events = Vec::new();
|
||||
for e in events {
|
||||
match e {
|
||||
HeartEvent::SetBlock(at, state) => self.level_set(at, state)?,
|
||||
HeartEvent::Sound(name, at, volume, pitch) => {
|
||||
self.audio
|
||||
.play(&format!("minecraft:{name}"), Some(at), volume, pitch)
|
||||
}
|
||||
HeartEvent::Trail {
|
||||
at,
|
||||
target,
|
||||
color,
|
||||
duration,
|
||||
} => self.particles.add(
|
||||
&ParticleOptions::trail(target, color, duration),
|
||||
at,
|
||||
[0.0; 3],
|
||||
),
|
||||
HeartEvent::OutputChanged(at) => self.container_changed((at[0], at[1], at[2])),
|
||||
HeartEvent::Mob(event) => mob_events.push(event),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// The state a face of resin can be added to: air, a source of water, or
|
||||
/// a clump already there.
|
||||
fn resin_clump_for(&self, neighbour: BlockStateId) -> Option<BlockStateId> {
|
||||
let registry = self.res.assets.registry;
|
||||
let clump = registry.default_state("minecraft:resin_clump")?;
|
||||
let facts = self.res.facts.get(neighbour);
|
||||
if self.res.facts.is_air(neighbour) {
|
||||
Some(clump)
|
||||
} else if &*facts.name == "minecraft:water"
|
||||
&& facts.fluid_level == 8
|
||||
&& !facts.fluid_falling
|
||||
{
|
||||
let mut s = registry.state(clump)?.clone();
|
||||
s.properties.insert("waterlogged".into(), "true".into());
|
||||
registry.resolve(&s).ok()
|
||||
} else if &*facts.name == "minecraft:resin_clump" {
|
||||
Some(neighbour)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn prop_is(&self, state: BlockStateId, key: &str) -> bool {
|
||||
self.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get(key))
|
||||
.is_some_and(|v| v == "true")
|
||||
}
|
||||
fn with_face(&self, state: BlockStateId, face: &str) -> Option<BlockStateId> {
|
||||
let mut s = self.res.assets.registry.state(state)?.clone();
|
||||
s.properties.insert(face.to_owned(), "true".to_owned());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
self.handle_mob_events(mob_events)?;
|
||||
let _ = key;
|
||||
Ok(())
|
||||
}
|
||||
/// A creaking bound to the heart at `home` was hurt (`creakingHurt`).
|
||||
pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) {
|
||||
pub(super) fn creaking_hurt(&mut self, home: [i32; 3], _id: u32, by_player: bool) {
|
||||
if !by_player {
|
||||
return;
|
||||
}
|
||||
@@ -255,29 +171,9 @@ impl Game<'_> {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 {
|
||||
self.heart_emit(&mut heart, key, 20, false);
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if self.heart_state_name(state) == "awake" {
|
||||
let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0);
|
||||
for _ in 0..clumps {
|
||||
if let Some(at) = self.heart_spread_resin(key) {
|
||||
self.audio.play(
|
||||
"minecraft:block.resin.place",
|
||||
Some([
|
||||
f64::from(at.0) + 0.5,
|
||||
f64::from(at.1) + 0.5,
|
||||
f64::from(at.2) + 0.5,
|
||||
]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
heart.emitter = 100;
|
||||
heart.emitter_target = self.mob_center(id).map(|(c, _)| c);
|
||||
}
|
||||
let _ = self.with_heart(key, &mut heart, |h, w, lr, host, out| {
|
||||
creaking_heart::creaking_hurt(h, home, w, lr, host, out);
|
||||
});
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
@@ -331,9 +227,18 @@ impl Game<'_> {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.heart_remove_protector(&mut heart, true);
|
||||
let _ = self.with_heart(key, &mut heart, |h, _, _, host, out| {
|
||||
creaking_heart::remove_protector(h, host, true, out);
|
||||
});
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if self.prop_is(state, "natural") && !self.creative && !self.spectator() {
|
||||
let natural = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("natural").cloned())
|
||||
.is_some_and(|v| v == "true");
|
||||
if natural && !self.creative && !self.spectator() {
|
||||
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
|
||||
self.spawn_orbs(
|
||||
[
|
||||
@@ -348,96 +253,6 @@ impl Game<'_> {
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
}
|
||||
/// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`.
|
||||
fn spawn_protector(&mut self, pos: Pos) -> Option<u32> {
|
||||
let t = self.res.mob_types.get("minecraft:creaking").cloned()?;
|
||||
for _ in 0..5 {
|
||||
let r = &mut self.world.random;
|
||||
let dx = r.next_int_bound(33).unwrap_or(16) - 16;
|
||||
let dz = r.next_int_bound(33).unwrap_or(16) - 16;
|
||||
let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz);
|
||||
if !self.world.loaded(at.0, at.2) {
|
||||
continue;
|
||||
}
|
||||
// moveToPossibleSpawnPosition: scan down for a collider with room above.
|
||||
let mut above = self.world.block(at.0, at.1, at.2);
|
||||
let mut found = false;
|
||||
for _ in 0..=16 {
|
||||
at.1 -= 1;
|
||||
let current = self.world.block(at.0, at.1, at.2);
|
||||
let facts = self.res.facts.get(current);
|
||||
let leaves = self
|
||||
.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:leaves")
|
||||
.is_some_and(|s| s.contains(&*facts.name));
|
||||
let clear_above = self
|
||||
.res
|
||||
.behaviours
|
||||
.collision_shape(above)
|
||||
.map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty());
|
||||
if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 {
|
||||
at.1 += 1;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
above = current;
|
||||
}
|
||||
if !found {
|
||||
continue;
|
||||
}
|
||||
// noCollision(spawn box) and no liquid.
|
||||
let w = t.width / 2.0;
|
||||
let bounds = Aabb::new(
|
||||
horizon_core::geometry::Vec3::new(
|
||||
f64::from(at.0) + 0.5 - w,
|
||||
f64::from(at.1),
|
||||
f64::from(at.2) + 0.5 - w,
|
||||
),
|
||||
horizon_core::geometry::Vec3::new(
|
||||
f64::from(at.0) + 0.5 + w,
|
||||
f64::from(at.1) + t.height,
|
||||
f64::from(at.2) + 0.5 + w,
|
||||
),
|
||||
);
|
||||
let mut scene = horizon_client::collisions::SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let free = scene.unobstructed(bounds).unwrap_or(false);
|
||||
let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid
|
||||
!= horizon_client::blocks::Fluid::None;
|
||||
if !free || wet {
|
||||
continue;
|
||||
}
|
||||
let id = self.spawn_mob(
|
||||
"minecraft:creaking",
|
||||
[
|
||||
f64::from(at.0) + 0.5,
|
||||
f64::from(at.1),
|
||||
f64::from(at.2) + 0.5,
|
||||
],
|
||||
false,
|
||||
)?;
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
creaking::set_transient(m, [pos.0, pos.1, pos.2]);
|
||||
}
|
||||
return Some(id);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.computeAnalogOutputSignal`.
|
||||
fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 {
|
||||
if heart.creaking.is_none() {
|
||||
return 0;
|
||||
}
|
||||
let Some(id) = self.heart_protector(heart) else {
|
||||
return 0;
|
||||
};
|
||||
let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0;
|
||||
15 - (distance * 15.0).floor() as i32
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.serverTick` for every heart.
|
||||
pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> {
|
||||
let keys: Vec<Pos> = self
|
||||
@@ -456,11 +271,17 @@ impl Game<'_> {
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
|
||||
// The block is gone: preRemoveSideEffects.
|
||||
self.heart_remove_protector(&mut heart, false);
|
||||
self.with_heart(key, &mut heart, |h, _, _, host, out| {
|
||||
creaking_heart::remove_protector(h, host, false, out);
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
// getTicker: none once uprooted.
|
||||
if self.heart_state_name(state) != "uprooted" {
|
||||
self.heart_tick(&mut heart, key, state)?;
|
||||
let pos = [key.0, key.1, key.2];
|
||||
self.with_heart(key, &mut heart, |h, w, lr, host, out| {
|
||||
creaking_heart::server_tick(h, pos, w, lr, host, out);
|
||||
})?;
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
@@ -469,139 +290,11 @@ impl Game<'_> {
|
||||
self.scan_for_hearts();
|
||||
Ok(())
|
||||
}
|
||||
fn heart_tick(
|
||||
&mut self,
|
||||
heart: &mut CreakingHeart,
|
||||
key: Pos,
|
||||
state: BlockStateId,
|
||||
) -> Result<()> {
|
||||
heart.ticks_existed += 1;
|
||||
let output = self.heart_output(heart, key);
|
||||
if output != heart.output_signal {
|
||||
heart.output_signal = output;
|
||||
self.container_changed(key);
|
||||
}
|
||||
if heart.emitter > 0 {
|
||||
if heart.emitter > 50 {
|
||||
self.heart_emit(heart, key, 1, true);
|
||||
self.heart_emit(heart, key, 1, false);
|
||||
}
|
||||
if heart.emitter % 10 == 0 && heart.emitter_target.is_some() {
|
||||
if let Some(id) = self.heart_protector(heart)
|
||||
&& let Some((c, _)) = self.mob_center(id)
|
||||
{
|
||||
heart.emitter_target = Some(c);
|
||||
}
|
||||
if let Some(target) = heart.emitter_target {
|
||||
let center = [
|
||||
f64::from(key.0) + 0.5,
|
||||
f64::from(key.1) + 0.5,
|
||||
f64::from(key.2) + 0.5,
|
||||
];
|
||||
let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0;
|
||||
let at = [
|
||||
(center[0] - target[0]) * progress + target[0],
|
||||
(center[1] - target[1]) * progress + target[1],
|
||||
(center[2] - target[2]) * progress + target[2],
|
||||
];
|
||||
let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5;
|
||||
self.audio
|
||||
.play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0);
|
||||
}
|
||||
}
|
||||
heart.emitter -= 1;
|
||||
}
|
||||
let ticker = heart.ticker;
|
||||
heart.ticker -= 1;
|
||||
if ticker >= 0 {
|
||||
return Ok(());
|
||||
}
|
||||
heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20;
|
||||
// updateCreakingState: logs gone and no creaking means uprooted.
|
||||
let active = self.creaking_active();
|
||||
let has_logs = self.with_level(|b, level, ticks| {
|
||||
b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state)
|
||||
});
|
||||
let wanted = if !has_logs && heart.creaking.is_none() {
|
||||
"uprooted"
|
||||
} else if active {
|
||||
"awake"
|
||||
} else {
|
||||
"dormant"
|
||||
};
|
||||
let mut current = self.heart_state_name(state);
|
||||
if wanted != current
|
||||
&& let Some(next) = self.heart_with_state(state, wanted)
|
||||
{
|
||||
self.level_set([key.0, key.1, key.2], next)?;
|
||||
current = wanted.to_owned();
|
||||
if wanted == "uprooted" {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if heart.creaking.is_none() {
|
||||
if current == "awake" && self.spawning_monsters() {
|
||||
let near = self.player.as_ref().is_some_and(|p| {
|
||||
let (dx, dy, dz) = (
|
||||
p.position.x - (f64::from(key.0) + 0.5),
|
||||
p.position.y - (f64::from(key.1) + 0.5),
|
||||
p.position.z - (f64::from(key.2) + 0.5),
|
||||
);
|
||||
dx * dx + dy * dy + dz * dz < 32.0 * 32.0
|
||||
}) && !self.spectator();
|
||||
if near && let Some(id) = self.spawn_protector(key) {
|
||||
let uuid = self.uuid_for(id);
|
||||
heart.creaking = Some((Some(id), uuid));
|
||||
heart.ticks_existed = 0;
|
||||
let at = self.mob_center(id).map(|(c, _)| c);
|
||||
self.audio
|
||||
.play("minecraft:entity.creaking.spawn", at, 1.0, 1.0);
|
||||
self.audio.play(
|
||||
"minecraft:block.creaking_heart.spawn",
|
||||
Some([
|
||||
f64::from(key.0) + 0.5,
|
||||
f64::from(key.1) + 0.5,
|
||||
f64::from(key.2) + 0.5,
|
||||
]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = self.heart_protector(heart) {
|
||||
let persistent = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.is_some_and(|m| m.persistent);
|
||||
let eye = self.player_view().map(|v| v.eye);
|
||||
let stuck = self
|
||||
.mobs
|
||||
.iter_mut()
|
||||
.find(|m| m.id == id)
|
||||
.is_some_and(|m| creaking::player_is_stuck(m, eye));
|
||||
if (!active && !persistent)
|
||||
|| self.heart_distance_to_creaking(id, key) > TOO_FAR
|
||||
|| stuck
|
||||
{
|
||||
self.heart_remove_protector(heart, false);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option<BlockStateId> {
|
||||
let mut s = self.res.assets.registry.state(state)?.clone();
|
||||
s.properties
|
||||
.insert("creaking_heart_state".to_owned(), wanted.to_owned());
|
||||
self.res.assets.registry.resolve(&s).ok()
|
||||
}
|
||||
/// `ServerLevel.isSpawningMonsters`.
|
||||
fn spawning_monsters(&self) -> bool {
|
||||
self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters")
|
||||
}
|
||||
/// `EnvironmentAttributes.CREAKING_ACTIVE`.
|
||||
pub(super) fn creaking_active(&mut self) -> bool {
|
||||
self.with_level(|b, level, ticks| b.creaking_active(level, ticks))
|
||||
self.ui.difficulty != 0
|
||||
&& self.ui.rules.bool("spawn_mobs")
|
||||
&& self.ui.rules.bool("spawn_monsters")
|
||||
}
|
||||
/// Hearts that came with generated or loaded chunks get their block
|
||||
/// entity (`newBlockEntity`) the first time their chunk is seen.
|
||||
|
||||
@@ -86,7 +86,7 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
|
||||
.full_collision
|
||||
}
|
||||
}
|
||||
fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
|
||||
pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
|
||||
let villager = m.species() == Species::Villager;
|
||||
Seen {
|
||||
id: m.id,
|
||||
@@ -135,6 +135,11 @@ fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
|
||||
.flatten(),
|
||||
profession: m.extra.variant2,
|
||||
xp: horizon_client::mobs::villager::xp(m),
|
||||
stats: [
|
||||
f64::from(m.attrs.max_health),
|
||||
m.extra.vector[0],
|
||||
m.attrs.speed,
|
||||
],
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
@@ -174,6 +179,7 @@ impl Game<'_> {
|
||||
yaw: self.yaw,
|
||||
hero: self.potions.effects.get("hero_of_the_village").is_some(),
|
||||
uuid: self.level.player_uuid.unwrap_or_default(),
|
||||
allies: std::sync::Arc::new(self.player_allies()),
|
||||
})
|
||||
}
|
||||
/// Biome facts at a position for finalizeSpawn and variant rules.
|
||||
@@ -374,6 +380,7 @@ impl Game<'_> {
|
||||
end: self.dim == Dim::End,
|
||||
world_seed: self.level.seed,
|
||||
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
|
||||
teams: self.mob_teams(),
|
||||
difficulty: self.local_difficulty(
|
||||
self.player
|
||||
.as_ref()
|
||||
@@ -446,36 +453,74 @@ impl Game<'_> {
|
||||
self.tick_patrol_spawner();
|
||||
}
|
||||
self.tick_raids();
|
||||
self.tick_creature_entities()
|
||||
}
|
||||
/// The entity phase of `tick_creatures`: every mob's tick, deaths, and the
|
||||
/// projectiles and effects that follow from them.
|
||||
pub(super) fn tick_creature_entities(&mut self) -> Result<()> {
|
||||
// LivingEntity.die runs when the killing blow lands: mobs killed
|
||||
// since the last tick (by the player, explosions...) die first.
|
||||
let killed: Vec<Mob> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| !m.alive() && !m.removed && !self.died.contains(&m.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
for m in killed {
|
||||
self.died.insert(m.id);
|
||||
self.mob_died(&m);
|
||||
}
|
||||
let uuid = self.level.player_uuid;
|
||||
let snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
|
||||
let mut snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
|
||||
let mut events = Vec::new();
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
let mut dead = Vec::new();
|
||||
let mut died = std::mem::take(&mut self.died);
|
||||
let level_random;
|
||||
{
|
||||
let w = self.mob_world_base(&snapshot);
|
||||
// The level random, lent to the mobs (brain behaviours draw from
|
||||
// it) and taken back after their ticks.
|
||||
let mut scratch = self.world.random.clone();
|
||||
let mut pushes = Vec::new();
|
||||
mobs.retain_mut(|m| {
|
||||
let mut keep = Vec::with_capacity(mobs.len());
|
||||
for i in 0..mobs.len() {
|
||||
let w = self.mob_world_base(&snapshot);
|
||||
let m = &mut mobs[i];
|
||||
if !w
|
||||
.world
|
||||
.loaded(m.position.x.floor() as i32, m.position.z.floor() as i32)
|
||||
{
|
||||
return !m.hostile() || m.persistent;
|
||||
keep.push(!m.hostile() || m.persistent);
|
||||
continue;
|
||||
}
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
let keep = m.tick(&w, &mut scratch, &mut events);
|
||||
let kept = m.tick(&w, &mut scratch, &mut events);
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
if !keep && !m.alive() && !m.removed {
|
||||
// Killed during its own tick (drowning, burning, falling...).
|
||||
if !m.alive() && !m.removed && died.insert(m.id) {
|
||||
dead.push(m.clone());
|
||||
}
|
||||
keep
|
||||
});
|
||||
if !kept {
|
||||
died.remove(&m.id);
|
||||
}
|
||||
keep.push(kept);
|
||||
// ServerLevel ticks entities one after another: the ones
|
||||
// after this mob see it as it is now.
|
||||
snapshot[i] = seen(m, uuid);
|
||||
snapshot[i].alive &= kept;
|
||||
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
|
||||
}
|
||||
let mut flags = keep.into_iter();
|
||||
mobs.retain(|_| flags.next().unwrap_or(true));
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
level_random = scratch;
|
||||
}
|
||||
self.world.random = level_random;
|
||||
self.mobs.append(&mut mobs);
|
||||
self.died = died;
|
||||
self.sync_riders();
|
||||
self.tick_skeleton_traps();
|
||||
self.tick_apparition();
|
||||
@@ -528,6 +573,10 @@ impl Game<'_> {
|
||||
self.villager_murdered(m, by_player);
|
||||
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
|
||||
self.drop_death_loot(&mut dying, by_player, consumed, pos);
|
||||
if m.species() == Species::CopperGolem {
|
||||
// CopperGolem.dropEquipment: the preserved equipment too.
|
||||
self.golem_drop_equipment(&mut dying);
|
||||
}
|
||||
if m.species() == Species::SulfurCube {
|
||||
self.split_sulfur_cube(m);
|
||||
}
|
||||
@@ -638,7 +687,8 @@ impl Game<'_> {
|
||||
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
|
||||
for e in events {
|
||||
match e {
|
||||
MobEvent::Sound(name, at, volume, pitch) => {
|
||||
MobEvent::Sound(name, at, volume, pitch)
|
||||
| MobEvent::LocalSound(name, at, volume, pitch) => {
|
||||
self.audio
|
||||
.play(&format!("minecraft:{name}"), Some(at), volume, pitch)
|
||||
}
|
||||
@@ -693,18 +743,21 @@ impl Game<'_> {
|
||||
MobEvent::Shoot(..) => {}
|
||||
MobEvent::Explode(at, radius) => {
|
||||
// The exploding mob causes the damage (Creeper.explodeCreeper).
|
||||
if let Some(id) = self
|
||||
let source_mob = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
(m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0
|
||||
})
|
||||
.map(|m| m.id)
|
||||
.next()
|
||||
{
|
||||
.next();
|
||||
if let Some(id) = source_mob {
|
||||
self.note_attacker("minecraft:explosion", id);
|
||||
}
|
||||
self.explode(at, radius)?
|
||||
self.combat.explosion_source = source_mob;
|
||||
let result = self.explode(at, radius);
|
||||
self.combat.explosion_source = None;
|
||||
result?
|
||||
}
|
||||
MobEvent::AttackMob {
|
||||
target,
|
||||
@@ -755,6 +808,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
},
|
||||
MobEvent::Gift { target, item } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target)
|
||||
&& m.saddle_item().is_none()
|
||||
{
|
||||
m.set_saddle(Some(ItemStack::new(item, 1)));
|
||||
}
|
||||
}
|
||||
MobEvent::HurtSelf { mob, kind, amount } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
m.damage(amount, horizon_client::mobs::Damage::of(kind));
|
||||
@@ -876,7 +936,21 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
},
|
||||
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
|
||||
MobEvent::Breed {
|
||||
parent,
|
||||
partner,
|
||||
llama,
|
||||
} => self.breed(parent, partner, llama),
|
||||
MobEvent::LockGaze { mob, partner } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
horizon_client::mobs::animal_brain::lock_gaze(m, partner);
|
||||
}
|
||||
}
|
||||
MobEvent::BreedTarget { mob, partner } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
horizon_client::mobs::animal_brain::set_breed_partner(m, partner);
|
||||
}
|
||||
}
|
||||
MobEvent::LeashBreak { mob, drop, sound } => self.break_leash(mob, drop, sound),
|
||||
MobEvent::Vibration { from, to, ticks } => {
|
||||
self.mob_vibration_particle(from, to, ticks)
|
||||
@@ -961,7 +1035,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Animal.spawnChildFromBreeding
|
||||
fn breed(&mut self, parent: u32, partner: u32) {
|
||||
fn breed(
|
||||
&mut self,
|
||||
parent: u32,
|
||||
partner: u32,
|
||||
llama: Option<Box<horizon_client::mobs::llama::Offspring>>,
|
||||
) {
|
||||
let Some(p) = self.mobs.iter().find(|m| m.id == parent).cloned() else {
|
||||
return;
|
||||
};
|
||||
@@ -1014,6 +1093,12 @@ impl Game<'_> {
|
||||
&& let Some(child) = self.mobs.iter_mut().find(|m| m.id == id)
|
||||
{
|
||||
child.extra.age = -24000;
|
||||
// A llama's baby was drawn in the parent's tick, with the
|
||||
// experience.
|
||||
if let Some(o) = llama {
|
||||
horizon_client::mobs::llama::apply_offspring(child, &o);
|
||||
return;
|
||||
}
|
||||
if horizon_client::mobs::equine::is_equine(p.species()) {
|
||||
let other = q.clone().unwrap_or_else(|| p.clone());
|
||||
let mut r = self.world.random.clone();
|
||||
@@ -1271,7 +1356,13 @@ impl Game<'_> {
|
||||
.filter(|m| m.alive() && m.species() == Species::Breeze)
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
let jitter = self.world.random.next_float();
|
||||
// Drawn only when a breeze could deflect a projectile: an empty
|
||||
// level must not move the level random every tick.
|
||||
let jitter = if breezes.is_empty() || projectiles.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
self.world.random.next_float()
|
||||
};
|
||||
let w = self.mob_world_base(&[]);
|
||||
let pw = ProjWorld { w: &w, targets };
|
||||
projectiles.retain_mut(|p| {
|
||||
@@ -1728,6 +1819,10 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
if self.interact_copper_golem(index, &item) {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
// AbstractHorse.mobInteract: feed, equip or ride.
|
||||
if self.interact_mount(index, &item) {
|
||||
self.swing_arm();
|
||||
|
||||
@@ -13,6 +13,7 @@ use horizon_client::{
|
||||
containers::BlockEntity,
|
||||
gamerules::Value as RuleValue,
|
||||
item_data::{canon_stack, parse_stack},
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Species},
|
||||
projectiles::ProjectileKind,
|
||||
world::World,
|
||||
@@ -38,6 +39,14 @@ pub(super) fn record(line: impl FnOnce() -> String) {
|
||||
}
|
||||
});
|
||||
}
|
||||
/// Start recording level and game event lines (another fixture's case).
|
||||
pub(super) fn start_recording() {
|
||||
LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
|
||||
}
|
||||
/// The lines recorded since `start_recording`; recording stops.
|
||||
pub(super) fn stop_recording() -> Vec<String> {
|
||||
LOG.with(|log| log.borrow_mut().take()).unwrap_or_default()
|
||||
}
|
||||
/// `Level.levelEvent` lines for the level events the behaviour library reported.
|
||||
pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
|
||||
for event in events {
|
||||
@@ -179,13 +188,39 @@ impl Game<'_> {
|
||||
);
|
||||
let slot = item[3].as_u64().unwrap_or(0) as usize;
|
||||
let stack = parse_stack(item[4].as_str().unwrap_or("-"))?;
|
||||
if let Some(cell) = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_mut(&p)
|
||||
.and_then(|e| e.slots_mut().get_mut(slot))
|
||||
{
|
||||
*cell = stack;
|
||||
self.fixture_fill(p, slot, stack);
|
||||
}
|
||||
// CrafterBlock.newBlockEntity copies the state's triggered flag;
|
||||
// CrafterBlockEntity.setSlotState disables only empty slots.
|
||||
let crafter_positions: Vec<(i32, i32, i32)> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
for p in crafter_positions {
|
||||
let state = self.world.block(p.0, p.1, p.2);
|
||||
let triggered = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("triggered"))
|
||||
.is_some_and(|v| v == "true");
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&p) {
|
||||
c.triggered = triggered;
|
||||
c.state_triggered = Some(triggered);
|
||||
}
|
||||
}
|
||||
for d in case["disabled"].as_array().into_iter().flatten() {
|
||||
let p = (
|
||||
d[0].as_i64().unwrap_or(0) as i32,
|
||||
d[1].as_i64().unwrap_or(0) as i32,
|
||||
d[2].as_i64().unwrap_or(0) as i32,
|
||||
);
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&p) {
|
||||
c.set_slot_state(d[3].as_u64().unwrap_or(0) as usize, false);
|
||||
}
|
||||
}
|
||||
let mut targets = Vec::new();
|
||||
@@ -225,7 +260,15 @@ impl Game<'_> {
|
||||
pos[2].as_i64().unwrap_or(0) as i32,
|
||||
);
|
||||
let state = self.world.block(origin.x, origin.y, origin.z);
|
||||
self.dispense_from(origin, state)?;
|
||||
if let Some(op) = case.get("remove") {
|
||||
self.fixture_remove(origin, op)?;
|
||||
} else {
|
||||
self.dispense_from(origin, state)?;
|
||||
// CrafterBlockEntity.serverTick, the crafting animation running down.
|
||||
for _ in 0..case["ticks"].as_u64().unwrap_or(0) {
|
||||
self.tick_crafters();
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default();
|
||||
@@ -241,7 +284,11 @@ impl Game<'_> {
|
||||
containers.sort_unstable();
|
||||
for p in containers {
|
||||
let entity = &self.world.block_entities[&p];
|
||||
for (i, slot) in entity.slots().iter().enumerate() {
|
||||
let single = match entity {
|
||||
BlockEntity::Jukebox(j) => std::slice::from_ref(&j.record),
|
||||
_ => entity.slots(),
|
||||
};
|
||||
for (i, slot) in single.iter().enumerate() {
|
||||
if let Some(stack) = slot {
|
||||
out.push(format!(
|
||||
"inv {},{},{} {i} {}",
|
||||
@@ -253,6 +300,32 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut crafters: Vec<_> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter_map(|(p, e)| match e {
|
||||
BlockEntity::Crafter(c) => Some((*p, c)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
crafters.sort_unstable_by_key(|c| c.0);
|
||||
for (p, c) in crafters {
|
||||
let disabled: Vec<String> = (0..9)
|
||||
.filter(|&i| c.disabled[i])
|
||||
.map(|i| i.to_string())
|
||||
.collect();
|
||||
out.push(format!(
|
||||
"crafter {},{},{} ticks={} triggered={} signal={} disabled={}",
|
||||
p.0,
|
||||
p.1,
|
||||
p.2,
|
||||
c.crafting_ticks,
|
||||
c.triggered,
|
||||
c.redstone_signal(),
|
||||
disabled.join(",")
|
||||
));
|
||||
}
|
||||
self.fixture_entities(&old_mobs, &old_stands, &mut out);
|
||||
for (i, t) in targets.iter().enumerate() {
|
||||
out.push(self.fixture_describe(i, t));
|
||||
@@ -266,6 +339,112 @@ impl Game<'_> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A stack in a block entity's slot: a container's, a jukebox's record, a
|
||||
/// lectern's book, or the items of a block entity Horizon keeps as saved.
|
||||
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
|
||||
let jukebox =
|
||||
&*self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox";
|
||||
match self.world.block_entities.get_mut(&p) {
|
||||
Some(BlockEntity::Jukebox(j)) => j.record = stack,
|
||||
Some(BlockEntity::Lectern(l)) => l.book = stack,
|
||||
Some(e) => {
|
||||
if let Some(cell) = e.slots_mut().get_mut(slot) {
|
||||
*cell = stack;
|
||||
}
|
||||
}
|
||||
None if jukebox => {
|
||||
// JukeboxBlockEntity holding its record (setSongItemWithoutPlaying).
|
||||
self.world.block_entities.insert(
|
||||
p,
|
||||
BlockEntity::Jukebox(horizon_client::containers::Jukebox {
|
||||
record: stack,
|
||||
ticks: 0,
|
||||
playing: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
None => self.fixture_fill_saved(p, slot, stack),
|
||||
}
|
||||
}
|
||||
/// The saved block entity of a campfire, decorated pot, chiseled
|
||||
/// bookshelf or shelf, as a loaded world keeps it.
|
||||
fn fixture_fill_saved(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
|
||||
use horizon_world::nbt::Tag;
|
||||
let name = self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(p.0, p.1, p.2))
|
||||
.name
|
||||
.clone();
|
||||
let id = match name.strip_prefix("minecraft:").unwrap_or(&name) {
|
||||
"campfire" | "soul_campfire" => "minecraft:campfire",
|
||||
"decorated_pot" => "minecraft:decorated_pot",
|
||||
"chiseled_bookshelf" => "minecraft:chiseled_bookshelf",
|
||||
n if n.ends_with("_shelf") => "minecraft:shelf",
|
||||
_ => return,
|
||||
};
|
||||
let Some(chunk) = self.world.chunks.get_mut(&(p.0 >> 4, p.2 >> 4)) else {
|
||||
return;
|
||||
};
|
||||
let chunk = Arc::make_mut(chunk);
|
||||
let saved = Arc::make_mut(chunk.saved.get_or_insert_with(Default::default));
|
||||
let at = |t: &Tag| {
|
||||
t.get("x") == Some(&Tag::Int(p.0))
|
||||
&& t.get("y") == Some(&Tag::Int(p.1))
|
||||
&& t.get("z") == Some(&Tag::Int(p.2))
|
||||
};
|
||||
let index = match saved.block_entities.iter().position(at) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
saved.block_entities.push(Tag::compound([
|
||||
("id", Tag::String(id.into())),
|
||||
("x", Tag::Int(p.0)),
|
||||
("y", Tag::Int(p.1)),
|
||||
("z", Tag::Int(p.2)),
|
||||
]));
|
||||
saved.block_entities.len() - 1
|
||||
}
|
||||
};
|
||||
let Tag::Compound(map) = &mut saved.block_entities[index] else {
|
||||
return;
|
||||
};
|
||||
let Some(stack) = stack else { return };
|
||||
if id == "minecraft:decorated_pot" {
|
||||
map.insert("item".into(), horizon_client::save::item_to_nbt(&stack));
|
||||
return;
|
||||
}
|
||||
let mut item = horizon_client::save::item_to_nbt(&stack);
|
||||
if let Tag::Compound(c) = &mut item {
|
||||
c.insert("Slot".into(), Tag::Byte(slot as i8));
|
||||
}
|
||||
match map
|
||||
.entry("Items".into())
|
||||
.or_insert_with(|| Tag::List(Vec::new()))
|
||||
{
|
||||
Tag::List(list) => list.push(item),
|
||||
other => *other = Tag::List(vec![item]),
|
||||
}
|
||||
}
|
||||
/// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block.
|
||||
fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> {
|
||||
match op["op"].as_str().unwrap_or("") {
|
||||
"set" => {
|
||||
let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32);
|
||||
let flags = op["flags"].as_i64().unwrap_or(3) as i32;
|
||||
self.with_level(|b, level, ticks| b.set_block(level, ticks, origin, state, flags));
|
||||
}
|
||||
"destroy" => {
|
||||
let drop = op["drop"].as_bool().unwrap_or(true);
|
||||
self.with_level(|b, level, ticks| b.destroy_block(level, ticks, origin, drop));
|
||||
}
|
||||
"remove" => {
|
||||
self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false));
|
||||
}
|
||||
other => return Err(format!("unknown removal {other}").into()),
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
|
||||
/// `EntityType.create` and `snapTo` for one target: no spawn finalization.
|
||||
fn fixture_target(&mut self, e: &Value) -> Result<Target> {
|
||||
let kind = e["type"].as_str().unwrap_or("minecraft:pig");
|
||||
@@ -391,13 +570,17 @@ impl Game<'_> {
|
||||
let _ = write!(line, " {name}={item}x1");
|
||||
}
|
||||
}
|
||||
let ready = match s {
|
||||
Species::Sheep => Some(!x.sheared && !m.is_baby()),
|
||||
Species::Mooshroom => Some(!m.is_baby()),
|
||||
Species::Bogged => Some(!x.sheared),
|
||||
Species::SnowGolem => Some(!x.sheared),
|
||||
_ => None,
|
||||
};
|
||||
let ready =
|
||||
match s {
|
||||
Species::Sheep => Some(!x.sheared && !m.is_baby()),
|
||||
Species::Mooshroom => Some(!m.is_baby()),
|
||||
Species::Bogged => Some(!x.sheared),
|
||||
Species::SnowGolem => Some(!x.sheared),
|
||||
Species::CopperGolem => Some(self.golem_shearable(
|
||||
self.mobs.iter().position(|o| o.id == id).unwrap_or(0),
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(r) = ready {
|
||||
line.push_str(if r { " ready" } else { " unready" });
|
||||
}
|
||||
@@ -502,6 +685,15 @@ impl Game<'_> {
|
||||
let (p, v) = (b.position, b.velocity);
|
||||
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
|
||||
}
|
||||
for o in &self.orbs {
|
||||
let (p, v) = (o.position, o.velocity);
|
||||
out.push(line(
|
||||
"minecraft:experience_orb",
|
||||
[p.x, p.y, p.z],
|
||||
[v.x, v.y, v.z],
|
||||
"",
|
||||
));
|
||||
}
|
||||
for c in &self.carts {
|
||||
let (p, v) = (c.position, c.velocity);
|
||||
out.push(line(c.kind.id(), [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
|
||||
|
||||
@@ -387,7 +387,20 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.wind_charge.throw", Some(c), 0.5, pitch);
|
||||
}
|
||||
2000 => {
|
||||
1049 => self
|
||||
.audio
|
||||
.play("minecraft:block.crafter.craft", Some(c), 1.0, 1.0),
|
||||
1050 => self
|
||||
.audio
|
||||
.play("minecraft:block.crafter.fail", Some(c), 1.0, 1.0),
|
||||
// LevelEventHandler.shootParticles: smoke for dispensers, white
|
||||
// smoke out of a crafter's front.
|
||||
2000 | 2010 => {
|
||||
let particle = if id == 2010 {
|
||||
ParticleType::WhiteSmoke
|
||||
} else {
|
||||
ParticleType::Smoke
|
||||
};
|
||||
let s = match data {
|
||||
0 => [0, -1, 0],
|
||||
1 => [0, 1, 0],
|
||||
@@ -422,8 +435,7 @@ impl Game<'_> {
|
||||
sy * pow + r.next_gaussian() * 0.01,
|
||||
sz * pow + r.next_gaussian() * 0.01,
|
||||
];
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ParticleType::Smoke), p, v);
|
||||
self.particles.add(&ParticleOptions::simple(particle), p, v);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -1706,7 +1718,12 @@ impl Game<'_> {
|
||||
}
|
||||
/// `Entity.spawnAtLocation(level, stack, offset)`: an item at the entity's
|
||||
/// feet plus the offset, moving as `new ItemEntity` makes it.
|
||||
fn spawn_at_location(&mut self, at: Vec3, y_offset: f64, stack: ItemStack) -> [f64; 3] {
|
||||
pub(super) fn spawn_at_location(
|
||||
&mut self,
|
||||
at: Vec3,
|
||||
y_offset: f64,
|
||||
stack: ItemStack,
|
||||
) -> [f64; 3] {
|
||||
let v = new_item_motion();
|
||||
self.spawn_item(stack, [at.x, at.y + y_offset, at.z], v, 10);
|
||||
v
|
||||
@@ -1842,6 +1859,20 @@ impl Game<'_> {
|
||||
self.spawn_at_location(at, eye, stack);
|
||||
}
|
||||
}
|
||||
// CopperGolem.shear: the antenna's flower drops 1.5 up.
|
||||
Species::CopperGolem if self.golem_shearable(i) => {
|
||||
self.audio
|
||||
.play("minecraft:entity.copper_golem.shear", sound_at, 1.0, 1.0);
|
||||
let antenna = self.mobs[i].saddle_item();
|
||||
let id = self.mobs[i].id;
|
||||
// setItemSlot(EQUIPMENT_SLOT_ANTENNA, EMPTY): an unequip.
|
||||
self.mobs[i].set_saddle(None);
|
||||
let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None);
|
||||
self.post_game_event("minecraft:unequip", [at.x, at.y, at.z], ctx);
|
||||
if let Some(antenna) = antenna {
|
||||
self.spawn_at_location(at, 1.5, antenna);
|
||||
}
|
||||
}
|
||||
Species::Mooshroom if !m.is_baby() => {
|
||||
let variant = if m.extra.variant == 1 { "brown" } else { "red" };
|
||||
let height = f64::from(m.height());
|
||||
@@ -1912,7 +1943,7 @@ impl Game<'_> {
|
||||
}
|
||||
// Leashable.dropLeash: a lead item at the leashed entity's feet.
|
||||
let drop = |game: &mut Self, j: usize| {
|
||||
if game.mobs[j].extra.leash.take().is_some() {
|
||||
if horizon_client::mobs::leash::remove(&mut game.mobs[j]).is_some() {
|
||||
let at = game.mobs[j].position;
|
||||
game.spawn_at_location(at, 0.0, ItemStack::new("minecraft:lead", 1));
|
||||
}
|
||||
|
||||
@@ -191,6 +191,15 @@ impl Game<'_> {
|
||||
[d[0] / l, d[1] / l, d[2] / l]
|
||||
}
|
||||
};
|
||||
// `source.doTeamsAllowDamage(entity)`: the exploding mob spares its
|
||||
// team mates when its team has no friendly fire (they are still pushed).
|
||||
let exploding = self.combat.explosion_source;
|
||||
let teams_allow = |g: &Self, victim: Option<&horizon_client::scoreboard::Team>| {
|
||||
exploding.is_none_or(|id| {
|
||||
horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim)
|
||||
})
|
||||
};
|
||||
let player_hurtable = teams_allow(self, self.player_team());
|
||||
// Player.
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let feet = [p.position.x, p.position.y, p.position.z];
|
||||
@@ -217,7 +226,7 @@ impl Game<'_> {
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:explosion")
|
||||
{
|
||||
// Creative players are invulnerable to explosions.
|
||||
if !creative {
|
||||
if !creative && player_hurtable {
|
||||
hurt = p
|
||||
.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false);
|
||||
@@ -236,6 +245,7 @@ impl Game<'_> {
|
||||
// Mobs.
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
for m in mobs.iter_mut().filter(|m| m.alive()) {
|
||||
let hurtable = teams_allow(self, self.mob_team(m.id));
|
||||
let feet = [m.position.x, m.position.y, m.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
if dist > 1.0 {
|
||||
@@ -253,7 +263,7 @@ impl Game<'_> {
|
||||
attacker: None,
|
||||
from: Some(center),
|
||||
};
|
||||
if !m.damage(damage(dist, exposure), source) {
|
||||
if hurtable && !m.damage(damage(dist, exposure), source) {
|
||||
continue;
|
||||
}
|
||||
let dir = direction(eye);
|
||||
@@ -390,18 +400,30 @@ impl Game<'_> {
|
||||
}
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
let is_tnt = &*name == "minecraft:tnt";
|
||||
// Block.onExplosionHit: the drops copy from the block entity, which
|
||||
// then spills its contents as the block turns to air.
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if let Some(entity) = self.world.block_entities.get(&key).cloned() {
|
||||
let custom = self.world.block_names.get(&key).cloned();
|
||||
self.pending.record(pos, &entity, &name, custom);
|
||||
} else if let Some(tag) = super::spill::saved_entity(&self.world, pos) {
|
||||
self.pending.record_saved(pos, &tag);
|
||||
}
|
||||
if !is_tnt {
|
||||
let drops = self.res.items.block_drops_in(
|
||||
let dynamic = self.pending.dynamic(pos);
|
||||
let drops = self.res.items.block_drops_full(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
None,
|
||||
&dynamic,
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
);
|
||||
for stack in drops {
|
||||
for mut stack in drops {
|
||||
if &*stack.item == "minecraft:air" || stack.count == 0 {
|
||||
continue;
|
||||
}
|
||||
self.pending.attach(pos, &mut stack);
|
||||
// survives_explosion / explosion_decay: 1 / radius per stack.
|
||||
if interaction == BlockInteraction::DestroyWithDecay
|
||||
&& self.world.random.next_float() > 1.0 / radius
|
||||
@@ -411,17 +433,8 @@ impl Game<'_> {
|
||||
add_or_append_stack(stacks, stack, pos);
|
||||
}
|
||||
}
|
||||
let contents = self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
|
||||
let name = self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(pos[0], pos[1], pos[2]))
|
||||
.name
|
||||
.clone();
|
||||
self.pending.clear(pos);
|
||||
self.level_set(pos, self.world.air)?;
|
||||
if let Some(entity) = contents {
|
||||
self.release_contents(pos, entity, &name);
|
||||
}
|
||||
if is_tnt {
|
||||
self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ impl Game<'_> {
|
||||
let id = self.mobs[index].id;
|
||||
self.break_leash(id, true, false);
|
||||
let was_empty = self.mobs[index].rider.is_none();
|
||||
// addPassenger: the rider is not standing on top, so no still
|
||||
// timeout.
|
||||
self.mobs[index].extra.counter = 0;
|
||||
self.yaw = self.mobs[index].yaw;
|
||||
self.riding = Some(id);
|
||||
self.mount.reset_jump();
|
||||
@@ -62,6 +65,12 @@ impl Game<'_> {
|
||||
}
|
||||
/// Getting off lands on top of it.
|
||||
pub(super) fn dismount_happy_ghast(&mut self, id: u32) {
|
||||
// removePassenger: held still for half a second, and with no one
|
||||
// aboard the ghast forgets its home.
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.extra.counter = 10;
|
||||
m.ai.home = None;
|
||||
}
|
||||
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! golem. Players placing the pumpkin and dispensers share it.
|
||||
use super::Game;
|
||||
use horizon_client::Result;
|
||||
use horizon_world::chunk::BlockState;
|
||||
|
||||
impl Game<'_> {
|
||||
fn golem_block(&self, p: [i32; 3]) -> &str {
|
||||
@@ -49,9 +48,20 @@ impl Game<'_> {
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CarvedPumpkinBlock.canSpawnGolem`.
|
||||
/// `CarvedPumpkinBlock.canSpawnGolem`: a snow or iron golem base, or a
|
||||
/// copper block (`#minecraft:copper`) below.
|
||||
pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool {
|
||||
self.find_golem(head).is_some()
|
||||
self.find_golem(head).is_some() || self.copper_golem_base(head)
|
||||
}
|
||||
/// The copper golem pattern ("^", "#"): a block of `#minecraft:copper` under the head.
|
||||
fn copper_golem_base(&self, head: [i32; 3]) -> bool {
|
||||
let below = [head[0], head[1] - 1, head[2]];
|
||||
let name = self.golem_block(below);
|
||||
self.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:copper")
|
||||
.is_some_and(|t| t.contains(name))
|
||||
}
|
||||
/// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed.
|
||||
pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> {
|
||||
@@ -71,9 +81,9 @@ impl Game<'_> {
|
||||
self.create_triggered(kind, at, 0.0);
|
||||
self.update_pattern_blocks(&blocks)
|
||||
}
|
||||
/// Whether placing a golem head at `head` completes a snow or iron golem.
|
||||
/// Whether placing a golem head at `head` completes a golem.
|
||||
pub(super) fn completes_golem(&self, head: [i32; 3]) -> bool {
|
||||
self.find_golem(head).is_some()
|
||||
self.find_golem(head).is_some() || self.copper_golem_base(head)
|
||||
}
|
||||
/// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or
|
||||
/// wither has no spawn finalization and draws nothing from the level.
|
||||
@@ -124,57 +134,67 @@ impl Game<'_> {
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
/// A pumpkin on a copper block: the block turns into the matching copper
|
||||
/// chest (facing the pumpkin's way) and a copper golem appears where the
|
||||
/// pumpkin was (`CarvedPumpkinBlock.spawnGolemInWorld` with
|
||||
/// `CopperChestBlock.getFromCopperBlock`).
|
||||
/// The copper golem (`CarvedPumpkinBlock.trySpawnGolem`, after the snow
|
||||
/// and iron golems): both blocks clear, the golem appears where the
|
||||
/// pumpkin was, the copper block becomes the matching copper chest facing
|
||||
/// the pumpkin's way (`replaceCopperBlockWithChest`, flags 2) and the
|
||||
/// golem takes the block's weathering (`CopperGolem.spawn`).
|
||||
fn try_spawn_copper_golem(&mut self, head: [i32; 3]) -> Result<()> {
|
||||
let below = [head[0], head[1] - 1, head[2]];
|
||||
let registry = self.res.assets.registry;
|
||||
let name = self.golem_block(below).to_string();
|
||||
let Some(base) = name.strip_prefix("minecraft:") else {
|
||||
return Ok(());
|
||||
};
|
||||
let waxed = base.strip_prefix("waxed_").unwrap_or(base);
|
||||
if !matches!(
|
||||
waxed,
|
||||
"copper_block" | "exposed_copper" | "weathered_copper" | "oxidized_copper"
|
||||
) {
|
||||
if !self.copper_golem_base(head) {
|
||||
return Ok(());
|
||||
}
|
||||
let chest = format!(
|
||||
"minecraft:{}_chest",
|
||||
base.strip_suffix("_block").unwrap_or(base)
|
||||
);
|
||||
let below = [head[0], head[1] - 1, head[2]];
|
||||
let copper = self.world.block(below[0], below[1], below[2]);
|
||||
let pumpkin = self.world.block(head[0], head[1], head[2]);
|
||||
let registry = self.res.assets.registry;
|
||||
let facing = registry
|
||||
.state(pumpkin)
|
||||
.and_then(|s| s.properties.get("facing").cloned())
|
||||
.unwrap_or_else(|| "north".into());
|
||||
let chest_state = BlockState {
|
||||
name: chest.clone(),
|
||||
properties: [
|
||||
("facing".to_string(), facing),
|
||||
("type".to_string(), "single".to_string()),
|
||||
("waterlogged".to_string(), "false".to_string()),
|
||||
]
|
||||
.into(),
|
||||
};
|
||||
let Some(chest_id) = registry
|
||||
.id(&chest_state)
|
||||
.or_else(|| registry.default_state(&chest))
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
self.destroy_particles(head, pumpkin);
|
||||
self.level_set(head, self.world.air)?;
|
||||
self.level_set(below, chest_id)?;
|
||||
// getWeatherStateFromPattern: waxed blocks weather like their unwaxed form.
|
||||
let base = self
|
||||
.golem_block(below)
|
||||
.trim_start_matches("minecraft:")
|
||||
.trim_start_matches("waxed_");
|
||||
let weather = ["exposed", "weathered", "oxidized"]
|
||||
.iter()
|
||||
.position(|w| base.starts_with(w))
|
||||
.map_or(0, |i| i as u8 + 1);
|
||||
let cells = [head, below];
|
||||
self.clear_pattern_blocks(&cells)?;
|
||||
let at = [
|
||||
f64::from(head[0]) + 0.5,
|
||||
f64::from(head[1]) + 0.05,
|
||||
f64::from(head[2]) + 0.5,
|
||||
];
|
||||
let _ = self.spawn_mob("minecraft:copper_golem", at, false);
|
||||
Ok(())
|
||||
let id = self.create_triggered("minecraft:copper_golem", at, 0.0);
|
||||
self.update_pattern_blocks(&cells)?;
|
||||
let direction = match facing.as_str() {
|
||||
"south" => horizon_core::geometry::Direction::South,
|
||||
"west" => horizon_core::geometry::Direction::West,
|
||||
"east" => horizon_core::geometry::Direction::East,
|
||||
_ => horizon_core::geometry::Direction::North,
|
||||
};
|
||||
let pos = horizon_core::position::BlockPos::new(below[0], below[1], below[2]);
|
||||
let chest = self.with_level(|b, level, ticks| {
|
||||
b.copper_chest_from_block(level, ticks, copper, direction, pos)
|
||||
});
|
||||
if let Some(chest) = chest {
|
||||
self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, chest, 2));
|
||||
if let Some(entity) =
|
||||
horizon_client::containers::BlockEntity::for_block(&self.res.facts.get(chest).name)
|
||||
{
|
||||
self.world
|
||||
.block_entities
|
||||
.insert((below[0], below[1], below[2]), entity);
|
||||
}
|
||||
}
|
||||
if let Some(m) = id.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id)) {
|
||||
m.extra.variant = weather;
|
||||
let p = [m.position.x, m.position.y, m.position.z];
|
||||
self.audio
|
||||
.play("minecraft:entity.copper_golem.spawn", Some(p), 1.0, 1.0);
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,16 +125,13 @@ impl Game<'_> {
|
||||
};
|
||||
self.stop_song(pos);
|
||||
if let Some(record) = record {
|
||||
let r = &mut self.world.random;
|
||||
// offsetRandomXZ(random, 0.7)
|
||||
let dx = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0;
|
||||
let dz = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5 + dx,
|
||||
f64::from(pos[1]) + 1.01,
|
||||
f64::from(pos[2]) + 0.5 + dz,
|
||||
];
|
||||
self.spawn_item(record, at, [0.0, 0.0, 0.0], 10);
|
||||
// atLowerCornerWithOffset(pos, 0.5, 1.01, 0.5).offsetRandomXZ(random, 0.7);
|
||||
// `new ItemEntity` moves it with its own random.
|
||||
let at = horizon_world::level::removal::jukebox_pop_position(
|
||||
&mut self.world.random,
|
||||
horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
);
|
||||
self.spawn_item(record, at, super::dispenser::new_item_motion(), 10);
|
||||
}
|
||||
self.set_has_record(pos, false);
|
||||
self.jukebox_changed(pos);
|
||||
|
||||
@@ -76,7 +76,7 @@ impl Game<'_> {
|
||||
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
|
||||
return;
|
||||
};
|
||||
if m.extra.leash.take().is_none() {
|
||||
if horizon_client::mobs::leash::remove(m).is_none() {
|
||||
return;
|
||||
}
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a
|
||||
//! banner with a dye (and a pattern item for the special patterns), the
|
||||
//! six-layer limit, the scrolling pattern list and the banner preview.
|
||||
use super::{
|
||||
Game,
|
||||
stations::{INPUT, Station},
|
||||
};
|
||||
//! The loom screen (`LoomScreen`): the scrolling pattern list, the banner
|
||||
//! preview and the six-layer error. The menu itself (`LoomMenu`: slots,
|
||||
//! selectable patterns, the pattern buttons, quick moves, the result) runs on
|
||||
//! the verified engine, `horizon_client::menu`, through `Game::menu_session`.
|
||||
use super::{Game, stations::Kind};
|
||||
use horizon_client::{
|
||||
banner::{self, BannerLayer},
|
||||
hud::{HudBatch, Rect, rgba},
|
||||
items::ItemStack,
|
||||
screen_layout::{self, LoomView, ScreenDraw},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -24,6 +23,8 @@ pub(super) struct LoomState {
|
||||
pub(super) scroll: f32,
|
||||
pub(super) start_row: usize,
|
||||
pub(super) scrolling: bool,
|
||||
/// The inputs the screen last saw (`bannerStack`, `dyeStack`, `patternStack`).
|
||||
last_inputs: [Option<ItemStack>; 3],
|
||||
}
|
||||
impl LoomState {
|
||||
fn total_rows(&self) -> usize {
|
||||
@@ -32,9 +33,6 @@ impl LoomState {
|
||||
fn offscreen_rows(&self) -> i32 {
|
||||
self.total_rows() as i32 - 4
|
||||
}
|
||||
fn scroll_active(&self) -> bool {
|
||||
self.display && self.patterns.len() > 16
|
||||
}
|
||||
/// `startRow` for a scroller position.
|
||||
fn row_for(&self, offs: f32) -> usize {
|
||||
((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize
|
||||
@@ -65,138 +63,77 @@ pub(super) fn dye_color(name: &str) -> u32 {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `LoomMenu.slotsChanged` and the screen's `containerChanged`.
|
||||
pub(super) fn loom_changed(&self, s: &mut Station) {
|
||||
let banners = &self.res.stations.banners;
|
||||
let items = &self.res.items;
|
||||
let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref());
|
||||
/// `LoomScreen.containerChanged`: the error flag, whether the pattern
|
||||
/// buttons show (only when an input changed), and the scroller reset.
|
||||
pub(super) fn loom_screen_changed(&mut self) {
|
||||
let Some(s) = self.station.as_mut().filter(|s| s.kind == Kind::Loom) else {
|
||||
return;
|
||||
};
|
||||
let inputs = [
|
||||
s.inputs[0].clone(),
|
||||
s.inputs[1].clone(),
|
||||
s.inputs[2].clone(),
|
||||
];
|
||||
let l = &mut s.loom;
|
||||
let mut result = None;
|
||||
if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) {
|
||||
let valid = l.selected.is_some_and(|i| i < l.patterns.len());
|
||||
let previous = std::mem::take(&mut l.patterns);
|
||||
l.patterns = banners.selectable(s.inputs[2].as_ref());
|
||||
let shown = if l.patterns.len() == 1 {
|
||||
l.selected = Some(0);
|
||||
Some(l.patterns[0].clone())
|
||||
} else if !valid {
|
||||
l.selected = None;
|
||||
None
|
||||
} else {
|
||||
let value = previous[l.selected.unwrap_or(0)].clone();
|
||||
match l.patterns.iter().position(|p| *p == value) {
|
||||
Some(i) => {
|
||||
l.selected = Some(i);
|
||||
Some(value)
|
||||
}
|
||||
None => {
|
||||
l.selected = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
l.has_max = banner::has_max_layers(banner_stack);
|
||||
if let Some(pattern) = shown {
|
||||
if l.has_max {
|
||||
l.selected = None;
|
||||
} else if let Some(dye) = banners.loom_dye(items, dye_stack) {
|
||||
result = Some(banner::loom_result(banner_stack, &dye, &pattern));
|
||||
}
|
||||
}
|
||||
l.display = !l.has_max && !l.patterns.is_empty();
|
||||
} else {
|
||||
l.patterns.clear();
|
||||
l.selected = None;
|
||||
l.has_max = banner_in.is_some_and(banner::has_max_layers);
|
||||
l.display = false;
|
||||
l.has_max = inputs[0].as_ref().is_some_and(banner::has_max_layers);
|
||||
if inputs != l.last_inputs {
|
||||
l.display =
|
||||
inputs[0].is_some() && inputs[1].is_some() && !l.has_max && !l.patterns.is_empty();
|
||||
}
|
||||
if l.start_row >= l.total_rows() {
|
||||
l.start_row = 0;
|
||||
l.scroll = 0.0;
|
||||
}
|
||||
s.result = result;
|
||||
l.last_inputs = inputs;
|
||||
}
|
||||
/// The loom slots' `mayPlace`.
|
||||
pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) {
|
||||
let banners = &self.res.stations.banners;
|
||||
let ok = match input {
|
||||
0 => stack.item.ends_with("_banner"),
|
||||
1 => banners.loom_dye(&self.res.items, stack).is_some(),
|
||||
_ => banners.is_pattern_item(&self.res.items, stack),
|
||||
/// A sound the loom menu played: the result's once per tick.
|
||||
pub(super) fn loom_sound(&mut self, sound: &str) {
|
||||
let ticks = self.ticks;
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
(ok, 64)
|
||||
if s.last_sound == ticks {
|
||||
return;
|
||||
}
|
||||
s.last_sound = ticks;
|
||||
let pos = s.pos;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.audio.play(sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
/// The result slot's `onTake`: one banner and one dye are used up.
|
||||
pub(super) fn loom_taken(&mut self, s: &mut Station) {
|
||||
for slot in &mut s.inputs[..2] {
|
||||
if let Some(x) = slot.as_mut() {
|
||||
x.count -= 1;
|
||||
if x.count == 0 {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.inputs[0].is_none() || s.inputs[1].is_none() {
|
||||
s.loom.selected = None;
|
||||
}
|
||||
if s.last_sound != self.ticks {
|
||||
s.last_sound = self.ticks;
|
||||
let pos = s.pos;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
/// `LoomScreen.mouseClicked` on a pattern button: `clickMenuButton`, and
|
||||
/// the select sound when the menu took it.
|
||||
fn loom_button(&mut self, index: usize) -> bool {
|
||||
let mut taken = false;
|
||||
let flag = &mut taken;
|
||||
self.menu_session(|menu, env, _| {
|
||||
*flag = menu.button(env, index as i32);
|
||||
Some(*flag)
|
||||
});
|
||||
if taken {
|
||||
self.audio
|
||||
.play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
/// `LoomMenu.quickMoveStack` from an inventory slot.
|
||||
pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool {
|
||||
let banners = &self.res.stations.banners;
|
||||
let items = &self.res.items;
|
||||
let target = if stack.item.ends_with("_banner") {
|
||||
Some(INPUT)
|
||||
} else if banners.loom_dye(items, stack).is_some() {
|
||||
Some(INPUT + 1)
|
||||
} else if banners.is_pattern_item(items, stack) {
|
||||
Some(INPUT + 2)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match target {
|
||||
Some(t) => self.move_to(stack, &[t], false),
|
||||
None if (9..36).contains(&slot) => {
|
||||
let hotbar: Vec<usize> = (0..9).collect();
|
||||
self.move_to(stack, &hotbar, false)
|
||||
}
|
||||
None if slot < 9 => {
|
||||
let main: Vec<usize> = (9..36).collect();
|
||||
self.move_to(stack, &main, false)
|
||||
}
|
||||
None => false,
|
||||
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
|
||||
}
|
||||
taken
|
||||
}
|
||||
/// A left click inside the loom's pattern grid or scroller.
|
||||
pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool {
|
||||
let Some(s) = self.station.as_ref() else {
|
||||
let Some(start_row) = self
|
||||
.station
|
||||
.as_ref()
|
||||
.filter(|s| s.loom.display)
|
||||
.map(|s| s.loom.start_row)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let l = &s.loom;
|
||||
if !l.display {
|
||||
return false;
|
||||
}
|
||||
for row in 0..4 {
|
||||
for column in 0..4 {
|
||||
let index = (row + l.start_row) * 4 + column;
|
||||
let index = (row + start_row) * 4 + column;
|
||||
let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON);
|
||||
if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) {
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.loom.selected = Some(index);
|
||||
}
|
||||
self.audio
|
||||
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
|
||||
self.station_changed();
|
||||
if inside(local, x, y, BUTTON, BUTTON) && self.loom_button(index) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -270,8 +207,116 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `LoomScreen.extractBackground` after the background; returns the
|
||||
/// pattern name tooltip of the hovered button.
|
||||
/// Paints `screen_layout` calls at the menu origin (ox, oy): the container
|
||||
/// background and the dimmed world are drawn by the caller.
|
||||
pub(super) fn paint_screen(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
ox: f32,
|
||||
oy: f32,
|
||||
draws: &[ScreenDraw],
|
||||
background: bool,
|
||||
) -> Option<Vec<(String, u32)>> {
|
||||
let atlas = &self.res.atlas;
|
||||
let mut tooltip = None;
|
||||
let mut sheet: Option<String> = None;
|
||||
for d in draws {
|
||||
match d {
|
||||
ScreenDraw::Gradient { .. } => {}
|
||||
ScreenDraw::Blit {
|
||||
texture,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
tw,
|
||||
th,
|
||||
} => {
|
||||
if background {
|
||||
let name = texture
|
||||
.trim_start_matches("textures/")
|
||||
.trim_end_matches(".png");
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
name,
|
||||
[ox + *x as f32, oy + *y as f32, *w as f32, *h as f32],
|
||||
*tw as f32,
|
||||
*th as f32,
|
||||
);
|
||||
}
|
||||
}
|
||||
ScreenDraw::Sprite { id, x, y, .. } => batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/{id}"),
|
||||
ox + *x as f32,
|
||||
oy + *y as f32,
|
||||
),
|
||||
ScreenDraw::Banner {
|
||||
base,
|
||||
layers,
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
} => self.draw_flag(
|
||||
batch,
|
||||
[
|
||||
ox + *x0 as f32,
|
||||
oy + *y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
],
|
||||
base,
|
||||
layers,
|
||||
),
|
||||
ScreenDraw::Tooltip { key } => {
|
||||
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
|
||||
}
|
||||
ScreenDraw::SpriteOf { id } => sheet = Some(id.clone()),
|
||||
ScreenDraw::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => {
|
||||
let c = *color as u32;
|
||||
batch.fill(
|
||||
atlas,
|
||||
ox + *x0 as f32,
|
||||
oy + *y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8),
|
||||
);
|
||||
}
|
||||
ScreenDraw::Atlas { x0, y0, x1, y1, uv } => {
|
||||
if let Some(r) = sheet.as_ref().and_then(|n| atlas.sprites.get(n)).copied() {
|
||||
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
|
||||
let part = Rect {
|
||||
u0: r.u0 + uv[0] * du,
|
||||
u1: r.u0 + uv[1] * du,
|
||||
v0: r.v0 + uv[2] * dv,
|
||||
v1: r.v0 + uv[3] * dv,
|
||||
w: (x1 - x0) as u32,
|
||||
h: (y1 - y0) as u32,
|
||||
};
|
||||
batch.rect_uv(
|
||||
ox + *x0 as f32,
|
||||
oy + *y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
part,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tooltip
|
||||
}
|
||||
/// `LoomScreen.extractBackground` after the background (the verified
|
||||
/// `screen_layout::loom`); returns the hovered pattern's tooltip.
|
||||
pub(super) fn draw_loom(
|
||||
&mut self,
|
||||
batch: &mut HudBatch,
|
||||
@@ -281,102 +326,35 @@ impl Game<'_> {
|
||||
) -> Option<Vec<(String, u32)>> {
|
||||
let s = self.station.as_ref()?;
|
||||
let l = &s.loom;
|
||||
let atlas = &self.res.atlas;
|
||||
for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() {
|
||||
if s.inputs[i].is_none() {
|
||||
let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i];
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/slot/{icon}"),
|
||||
ox + pos.0,
|
||||
oy + pos.1,
|
||||
);
|
||||
}
|
||||
}
|
||||
let scroller = if l.scroll_active() {
|
||||
"scroller"
|
||||
} else {
|
||||
"scroller_disabled"
|
||||
};
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/loom/{scroller}"),
|
||||
ox + 119.0,
|
||||
oy + 13.0 + (41.0 * l.scroll).floor(),
|
||||
);
|
||||
let result = s.result.clone();
|
||||
let (display, has_max, start_row, selected) =
|
||||
(l.display, l.has_max, l.start_row, l.selected);
|
||||
let patterns = l.patterns.clone();
|
||||
let dye = s.inputs[1]
|
||||
.as_ref()
|
||||
.and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d))
|
||||
.unwrap_or_else(|| Arc::from("white"));
|
||||
if let Some(result) = result.filter(|_| !has_max)
|
||||
&& let Some(base) = banner::banner_color(&result.item)
|
||||
{
|
||||
self.draw_flag(
|
||||
batch,
|
||||
[ox + 141.0, oy + 8.0, 20.0, 40.0],
|
||||
base,
|
||||
banner::layers(&result),
|
||||
);
|
||||
} else if has_max {
|
||||
batch.sprite(
|
||||
&self.res.atlas,
|
||||
"gui/sprites/container/loom/error",
|
||||
ox + 138.0,
|
||||
oy + 52.0,
|
||||
);
|
||||
}
|
||||
let mut tooltip = None;
|
||||
if display {
|
||||
let atlas = &self.res.atlas;
|
||||
for row in 0..4 {
|
||||
for column in 0..4 {
|
||||
let index = (row + start_row) * 4 + column;
|
||||
let Some(pattern) = patterns.get(index) else {
|
||||
return tooltip;
|
||||
};
|
||||
let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON);
|
||||
let hover = inside(local, x, y, BUTTON, BUTTON);
|
||||
let sprite = if selected == Some(index) {
|
||||
"pattern_selected"
|
||||
} else if hover {
|
||||
let key = self
|
||||
.res
|
||||
.stations
|
||||
.banners
|
||||
.layer_key(&BannerLayer::new(pattern, &dye));
|
||||
tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]);
|
||||
"pattern_highlighted"
|
||||
} else {
|
||||
"pattern"
|
||||
};
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/loom/{sprite}"),
|
||||
ox + x,
|
||||
oy + y,
|
||||
);
|
||||
// extractBannerOnButton: a 5x10 grey cloth with the pattern.
|
||||
batch.fill(
|
||||
atlas,
|
||||
ox + x + 4.0,
|
||||
oy + y + 2.0,
|
||||
5.0,
|
||||
10.0,
|
||||
dye_color("gray"),
|
||||
);
|
||||
let texture = self.res.stations.banners.banner_texture(pattern);
|
||||
if let Some(r) = atlas.sprites.get(&texture).copied() {
|
||||
let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]);
|
||||
batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tooltip
|
||||
.and_then(|d| self.res.items.get(&d.item))
|
||||
.and_then(|i| i.dye.clone())
|
||||
.unwrap_or_else(|| "white".to_owned());
|
||||
let result = s
|
||||
.result
|
||||
.as_ref()
|
||||
.and_then(|r| Some((banner::banner_color(&r.item)?, banner::layers(r))));
|
||||
let view = LoomView {
|
||||
width: 176,
|
||||
height: 166,
|
||||
left: 0,
|
||||
top: 0,
|
||||
has_banner: s.inputs[0].is_some(),
|
||||
has_dye: s.inputs[1].is_some(),
|
||||
has_pattern: s.inputs[2].is_some(),
|
||||
patterns: &l.patterns,
|
||||
selected: l.selected.map_or(-1, |i| i as i32),
|
||||
display: l.display,
|
||||
has_max: l.has_max,
|
||||
scroll: l.scroll,
|
||||
start_row: l.start_row,
|
||||
result,
|
||||
dye: &dye,
|
||||
mouse: local,
|
||||
};
|
||||
let draws = screen_layout::loom(&view, &self.res.stations.banners);
|
||||
self.paint_screen(batch, ox, oy, &draws, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,7 +373,6 @@ mod tests {
|
||||
};
|
||||
// 40 patterns = 10 rows, 6 off screen.
|
||||
assert_eq!(l.offscreen_rows(), 6);
|
||||
assert!(l.scroll_active());
|
||||
assert_eq!(l.row_for(0.0), 0);
|
||||
assert_eq!(l.row_for(1.0), 6);
|
||||
assert_eq!(l.row_for(0.5), 3);
|
||||
@@ -409,7 +386,6 @@ mod tests {
|
||||
display: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!l.scroll_active());
|
||||
assert_eq!(l.offscreen_rows(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,8 @@ enum Kind {
|
||||
Hopper,
|
||||
/// `CrafterBlockEntity`: disabled slots and the smallest-stack-first rule.
|
||||
Crafter,
|
||||
/// `BrewingStandBlockEntity` (a `WorldlyContainer`).
|
||||
Brewing,
|
||||
}
|
||||
|
||||
/// A container: one block entity, or a double chest (`CompoundContainer`).
|
||||
@@ -66,6 +68,9 @@ impl View {
|
||||
(Kind::Furnace, Some(Direction::Down)) => vec![2, 1],
|
||||
(Kind::Furnace, Some(Direction::Up)) => vec![0],
|
||||
(Kind::Furnace, Some(_)) => vec![1],
|
||||
(Kind::Brewing, Some(Direction::Up)) => vec![3],
|
||||
(Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3],
|
||||
(Kind::Brewing, Some(_)) => vec![0, 1, 2, 4],
|
||||
_ => (0..self.len()).collect(),
|
||||
}
|
||||
}
|
||||
@@ -112,6 +117,8 @@ struct Containers<'a> {
|
||||
behaviours: &'a Behaviours,
|
||||
items: &'a Items,
|
||||
registry: &'static horizon_world::registry::BlockRegistry,
|
||||
/// Brewing recipes, for what a brewing stand accepts (not needed for signals).
|
||||
brewing: Option<&'a horizon_client::brewing::Brewing>,
|
||||
}
|
||||
impl Containers<'_> {
|
||||
fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> {
|
||||
@@ -140,6 +147,7 @@ impl Containers<'_> {
|
||||
let kind = match (entity, name) {
|
||||
(BlockEntity::Furnace(_), _) => Kind::Furnace,
|
||||
(BlockEntity::Crafter(_), _) => Kind::Crafter,
|
||||
(BlockEntity::Brewing(_), _) => Kind::Brewing,
|
||||
(_, "minecraft:hopper") => Kind::Hopper,
|
||||
_ => Kind::Generic,
|
||||
};
|
||||
@@ -209,10 +217,33 @@ impl Containers<'_> {
|
||||
fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool {
|
||||
if view.kind == Kind::Crafter {
|
||||
return match self.world.block_entities.get(&view.parts[0].0) {
|
||||
Some(BlockEntity::Crafter(c)) => c.can_place(slot, stack, self.max_stack(stack)),
|
||||
Some(BlockEntity::Crafter(c)) => {
|
||||
// The slot's own stack sets the limit (`slotStack.getMaxStackSize`).
|
||||
let max = c.items.get(slot).and_then(Option::as_ref).unwrap_or(stack);
|
||||
c.can_place(slot, stack, self.max_stack(max))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
if view.kind == Kind::Brewing {
|
||||
// BrewingStandBlockEntity.canPlaceItem
|
||||
return match slot {
|
||||
4 => self
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.is_some_and(|i| i.brewing_fuel.is_some()),
|
||||
3 => self.brewing.is_some_and(|b| b.is_reagent(stack)),
|
||||
_ => {
|
||||
let input = self.brewing.is_some_and(|b| b.is_bottle(stack))
|
||||
|| self
|
||||
.items
|
||||
.item_tags
|
||||
.get("minecraft:brewing_potion_inputs")
|
||||
.is_some_and(|m| m.contains(&*stack.item));
|
||||
input && self.get(view, slot).is_none()
|
||||
}
|
||||
};
|
||||
}
|
||||
if view.kind != Kind::Furnace {
|
||||
return true;
|
||||
}
|
||||
@@ -231,8 +262,11 @@ impl Containers<'_> {
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
/// `canTakeItemThroughFace` (only furnaces restrict it).
|
||||
/// `canTakeItemThroughFace` (furnaces and brewing stands restrict it).
|
||||
fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool {
|
||||
if view.kind == Kind::Brewing {
|
||||
return slot != 3 || &*stack.item == "minecraft:glass_bottle";
|
||||
}
|
||||
view.kind != Kind::Furnace
|
||||
|| face != Direction::Down
|
||||
|| slot != 1
|
||||
@@ -279,6 +313,7 @@ pub(super) fn container_signal(
|
||||
behaviours,
|
||||
items,
|
||||
registry,
|
||||
brewing: None,
|
||||
};
|
||||
c.view((pos.x, pos.y, pos.z), true)
|
||||
.map_or(0, |v| c.signal(&v))
|
||||
@@ -291,6 +326,7 @@ impl Game<'_> {
|
||||
behaviours: &self.res.behaviours,
|
||||
items: &self.res.items,
|
||||
registry: self.res.assets.registry,
|
||||
brewing: Some(&self.res.stations.brewing),
|
||||
}
|
||||
}
|
||||
fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option<ItemStack>> {
|
||||
@@ -346,9 +382,8 @@ impl Game<'_> {
|
||||
success = true;
|
||||
}
|
||||
Some(current)
|
||||
if current.item == stack.item
|
||||
&& current.damage == stack.damage
|
||||
&& current.count <= max =>
|
||||
// HopperBlockEntity.canMergeItems
|
||||
if current.count <= max && current.same_item_same_components(&stack) =>
|
||||
{
|
||||
let space = max.saturating_sub(current.count);
|
||||
let count = stack.count.min(space);
|
||||
@@ -380,7 +415,7 @@ impl Game<'_> {
|
||||
stack: ItemStack,
|
||||
face: Option<Direction>,
|
||||
) -> Option<ItemStack> {
|
||||
let slots = if view.kind == Kind::Furnace && face.is_some() {
|
||||
let slots = if matches!(view.kind, Kind::Furnace | Kind::Brewing) && face.is_some() {
|
||||
view.slots_for_face(face)
|
||||
} else {
|
||||
(0..view.len()).collect()
|
||||
|
||||
@@ -7,7 +7,6 @@ use horizon_client::{
|
||||
advancements as adv,
|
||||
containers::Crafter,
|
||||
hud::{HudBatch, rgba},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -67,6 +66,8 @@ impl Game<'_> {
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
let mut positions = positions;
|
||||
positions.sort_unstable();
|
||||
for pos in positions {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let triggered = self.containers().prop(state, "triggered") == Some("true");
|
||||
@@ -101,6 +102,7 @@ impl Game<'_> {
|
||||
return Ok(());
|
||||
};
|
||||
let grid: Vec<Option<ItemStack>> = crafter.items.to_vec();
|
||||
// RecipeCache.get: the first crafting recipe that matches, assembled.
|
||||
let found = self
|
||||
.res
|
||||
.recipes
|
||||
@@ -108,9 +110,7 @@ impl Game<'_> {
|
||||
.map(|(name, result)| (name.to_owned(), result))
|
||||
.filter(|(_, result)| result.count > 0);
|
||||
let Some((recipe, result)) = found else {
|
||||
// LevelEvent 1050: CRAFTER_FAIL.
|
||||
self.audio
|
||||
.play("minecraft:block.crafter.fail", Some(center(key)), 1.0, 1.0);
|
||||
self.dispenser_event(1050, key, 0);
|
||||
return Ok(());
|
||||
};
|
||||
let Some(facing) = self
|
||||
@@ -130,6 +130,7 @@ impl Game<'_> {
|
||||
true,
|
||||
horizon_world::level::flags::UPDATE_CLIENTS,
|
||||
);
|
||||
// The remainders come from the grid as it was before anything moved.
|
||||
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
|
||||
self.crafter_eject(key, facing, result, &recipe);
|
||||
for rest in remainders.into_iter().flatten() {
|
||||
@@ -184,38 +185,6 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.spawn_dispensed(pos, facing, rest, 6);
|
||||
// LevelEvent 1049 (CRAFTER_CRAFT) and 2010 (white smoke shot out the front).
|
||||
self.audio
|
||||
.play("minecraft:block.crafter.craft", Some(center(pos)), 1.0, 1.0);
|
||||
let s = step(facing);
|
||||
for _ in 0..10 {
|
||||
let r = &mut self.world.random;
|
||||
let pow = r.next_double() * 0.2 + 0.01;
|
||||
let at = [
|
||||
f64::from(pos.0)
|
||||
+ f64::from(s[0]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[0]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[2]) * 0.5,
|
||||
f64::from(pos.1)
|
||||
+ f64::from(s[1]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[1]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[1]) * 0.5,
|
||||
f64::from(pos.2)
|
||||
+ f64::from(s[2]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[2]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[0]) * 0.5,
|
||||
];
|
||||
let v = [
|
||||
f64::from(s[0]) * pow + r.next_gaussian() * 0.01,
|
||||
f64::from(s[1]) * pow + r.next_gaussian() * 0.01,
|
||||
f64::from(s[2]) * pow + r.next_gaussian() * 0.01,
|
||||
];
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ParticleType::WhiteSmoke), at, v);
|
||||
}
|
||||
// CrafterRecipeCraftedTrigger for players within the 17-block box.
|
||||
let near = self.eye_position().is_some_and(|e| {
|
||||
let c = center(pos);
|
||||
@@ -234,6 +203,8 @@ impl Game<'_> {
|
||||
adv::conditions(&c["player"], &ctx, w) && recipe_matches(&c["recipes"], &id)
|
||||
});
|
||||
}
|
||||
self.dispenser_event(1049, pos, 0);
|
||||
self.dispenser_event(2010, pos, facing as i32);
|
||||
}
|
||||
|
||||
// ---- the menu ----
|
||||
@@ -261,57 +232,42 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `CrafterScreen`'s background, title, disabled slots and powered arrow.
|
||||
/// `CrafterScreen`'s background, disabled slots and powered arrow (the
|
||||
/// verified `screen_layout::crafter`) and its centred title.
|
||||
pub(in crate::game) fn draw_crafter_screen(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
|
||||
let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else {
|
||||
return;
|
||||
};
|
||||
let powered = self
|
||||
.container
|
||||
.map(|k| self.world.block(k.0, k.1, k.2))
|
||||
.is_some_and(|state| self.containers().prop(state, "triggered") == Some("true"));
|
||||
let draws =
|
||||
horizon_client::screen_layout::crafter(&horizon_client::screen_layout::CrafterView {
|
||||
width: 176,
|
||||
height: 166,
|
||||
left: 0,
|
||||
top: 0,
|
||||
disabled: c.disabled,
|
||||
powered,
|
||||
});
|
||||
// The background goes first, then the labels, then the slot decorations.
|
||||
let (background, rest) = draws.split_at(2.min(draws.len()));
|
||||
self.paint_screen(batch, ox, oy, background, true);
|
||||
let atlas = &self.res.atlas;
|
||||
batch.sprite_region(
|
||||
atlas,
|
||||
"gui/container/crafter",
|
||||
[ox, oy, 176.0, 166.0],
|
||||
256.0,
|
||||
256.0,
|
||||
);
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
let title = self.container_title(self.translate("container.crafter", "Crafter"));
|
||||
let tw = HudBatch::text_width(atlas, &title);
|
||||
batch.text(
|
||||
atlas,
|
||||
&title,
|
||||
ox + (176.0 - tw) / 2.0,
|
||||
ox + ((176.0 - tw) / 2.0).trunc(),
|
||||
oy + 6.0,
|
||||
grey,
|
||||
false,
|
||||
);
|
||||
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
|
||||
for slot in 0..9 {
|
||||
if c.disabled[slot] {
|
||||
let (x, y) = self.crafter_slot_position(300 + slot).unwrap_or_default();
|
||||
batch.sprite(
|
||||
atlas,
|
||||
"gui/sprites/container/crafter/disabled_slot",
|
||||
ox + x - 1.0,
|
||||
oy + y - 1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
let powered = self
|
||||
.container
|
||||
.map(|k| self.world.block(k.0, k.1, k.2))
|
||||
.is_some_and(|state| self.containers().prop(state, "triggered") == Some("true"));
|
||||
let arrow = if powered {
|
||||
"powered_redstone"
|
||||
} else {
|
||||
"unpowered_redstone"
|
||||
};
|
||||
batch.sprite(
|
||||
atlas,
|
||||
&format!("gui/sprites/container/crafter/{arrow}"),
|
||||
ox + 97.0,
|
||||
oy + 35.0,
|
||||
);
|
||||
self.paint_screen(batch, ox, oy, rest, true);
|
||||
}
|
||||
/// `gui.togglable_slot` over an empty, enabled grid slot.
|
||||
pub(in crate::game) fn crafter_tooltip(&self, slot: usize) -> Option<String> {
|
||||
@@ -320,64 +276,67 @@ impl Game<'_> {
|
||||
(self.carried.is_none() && c.items[i].is_none() && !c.disabled[i] && !self.spectator())
|
||||
.then(|| self.translate("gui.togglable_slot", "Click to disable slot"))
|
||||
}
|
||||
/// A click in the crafter menu before the generic handling; true when
|
||||
/// it was fully handled (the result, shift-clicks).
|
||||
pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool) -> bool {
|
||||
/// A click in the crafter menu: `CrafterMenu` on the verified menu engine.
|
||||
pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool, right: bool) -> bool {
|
||||
if !self.crafter_open() {
|
||||
return false;
|
||||
}
|
||||
if slot == RESULT_SLOT {
|
||||
return true;
|
||||
}
|
||||
if (300..309).contains(&slot) {
|
||||
// CrafterScreen.slotClicked: toggle an empty slot.
|
||||
let i = slot - 300;
|
||||
if !shift && !self.spectator() && self.slot_mut(slot).is_none() {
|
||||
let carried_empty = self.carried.is_none();
|
||||
let key = self.container;
|
||||
let mut toggled = None;
|
||||
if let Some(BlockEntity::Crafter(c)) =
|
||||
key.and_then(|k| self.world.block_entities.get_mut(&k))
|
||||
{
|
||||
if c.disabled[i] {
|
||||
c.set_slot_state(i, true);
|
||||
toggled = Some(true);
|
||||
} else if carried_empty {
|
||||
c.set_slot_state(i, false);
|
||||
toggled = Some(false);
|
||||
}
|
||||
}
|
||||
if let Some(enabled) = toggled {
|
||||
let pitch = if enabled { 1.0 } else { 0.75 };
|
||||
self.audio
|
||||
.play("minecraft:ui.button.click", None, 0.4, pitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
if shift {
|
||||
self.crafter_quick_move(slot);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
let input = if shift {
|
||||
horizon_client::menu::Input::QuickMove
|
||||
} else {
|
||||
horizon_client::menu::Input::Pickup
|
||||
};
|
||||
self.menu_click(Some(slot), i32::from(right), input);
|
||||
true
|
||||
}
|
||||
/// `CrafterMenu.quickMoveStack`.
|
||||
fn crafter_quick_move(&mut self, slot: usize) {
|
||||
if slot >= 309 {
|
||||
/// `CrafterScreen.slotClicked`: an empty grid slot is enabled by a click
|
||||
/// (or a number key with a hotbar item) when disabled, and disabled by a
|
||||
/// click with nothing carried; the menu then gets the click itself.
|
||||
pub(in crate::game) fn crafter_slot_clicked(
|
||||
&mut self,
|
||||
slot: usize,
|
||||
button: i32,
|
||||
input: horizon_client::menu::Input,
|
||||
) {
|
||||
use horizon_client::menu::Input;
|
||||
if !self.crafter_open() || !(300..309).contains(&slot) || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let Some(mut stack) = self.slot_mut(slot).take() else {
|
||||
let i = slot - 300;
|
||||
let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else {
|
||||
return;
|
||||
};
|
||||
if slot >= 300 {
|
||||
let player: Vec<usize> = (9..36).chain(0..9).collect();
|
||||
self.move_to(&mut stack, &player, true);
|
||||
} else {
|
||||
let grid: Vec<usize> = (300..309).collect();
|
||||
self.move_to(&mut stack, &grid, false);
|
||||
}
|
||||
if stack.count > 0 {
|
||||
*self.slot_mut(slot) = Some(stack);
|
||||
if c.items[i].is_some() {
|
||||
return;
|
||||
}
|
||||
let disabled = c.disabled[i];
|
||||
let enable = match input {
|
||||
Input::Pickup if disabled => Some(true),
|
||||
Input::Pickup if self.carried.is_none() => Some(false),
|
||||
Input::Swap if disabled => usize::try_from(button)
|
||||
.ok()
|
||||
.and_then(|b| {
|
||||
if b == 40 {
|
||||
Some(&self.offhand)
|
||||
} else {
|
||||
self.inventory.get(b)
|
||||
}
|
||||
})
|
||||
.is_some_and(Option::is_some)
|
||||
.then_some(true),
|
||||
_ => None,
|
||||
};
|
||||
let Some(enabled) = enable else {
|
||||
return;
|
||||
};
|
||||
// ServerboundContainerSlotStateChangedPacket: CrafterBlockEntity.setSlotState.
|
||||
self.menu_session(|menu, _, _| {
|
||||
menu.set_slot_state(i, enabled);
|
||||
Some(true)
|
||||
});
|
||||
let pitch = if enabled { 1.0 } else { 0.75 };
|
||||
self.audio
|
||||
.play("minecraft:ui.button.click", None, 0.4, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Custom names: `NameTagItem.interactLivingEntity` and the name tag
|
||||
//! (`EntityRenderer.submitNameTag`): above the head, facing the camera,
|
||||
//! on a translucent black background, shown when the name is visible or the
|
||||
//! mob is under the crosshair within 64 blocks.
|
||||
//! mob is under the crosshair within 64 blocks, as its team's name tag
|
||||
//! visibility allows, in the team's colours, with its score in the
|
||||
//! objective displayed below names.
|
||||
use super::{Game, view_vector};
|
||||
use horizon_client::mesher::Vertex;
|
||||
use horizon_client::{mesher::Vertex, save::uuid_text, scoreboard as sb, text::Text};
|
||||
|
||||
impl Game<'_> {
|
||||
/// A named name tag names the mob under the crosshair.
|
||||
@@ -26,17 +28,37 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// `Entity.belowNameDisplay`: the mob's score in the objective shown below
|
||||
/// names, then a space and the objective's name.
|
||||
fn below_name_text(&self, id: u32) -> Option<Text> {
|
||||
let board = &self.score.board;
|
||||
let objective = board.display_objective(sb::SLOT_BELOW_NAME)?;
|
||||
let uuid = self.persist.uuids.get(&id)?;
|
||||
let score = board.score(&uuid_text(*uuid), &objective.name)?;
|
||||
// numberFormatOrDefault(StyledFormat.NO_STYLE).
|
||||
let format = score
|
||||
.number_format
|
||||
.clone()
|
||||
.or_else(|| objective.number_format.clone())
|
||||
.unwrap_or(sb::NumberFormat::Styled(serde_json::json!({})));
|
||||
let mut t = Text::empty();
|
||||
t.push(format.format(score.value));
|
||||
t.push(Text::literal(" "));
|
||||
t.push(objective.display_text());
|
||||
Some(t)
|
||||
}
|
||||
pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
let target = self.mob_hit().map(|(i, _)| self.mobs[i].id);
|
||||
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
|
||||
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
|
||||
let up = right.cross(forward).normalize_or_zero();
|
||||
let white = self.res.atlas.font.white();
|
||||
let viewer = self.player_team();
|
||||
for m in &self.mobs {
|
||||
let Some(name) = m.custom_name.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
if !(m.name_visible || Some(m.id) == target) || !m.alive() {
|
||||
if !m.alive() {
|
||||
continue;
|
||||
}
|
||||
let p = glam::DVec3::new(
|
||||
@@ -44,19 +66,48 @@ impl Game<'_> {
|
||||
m.previous.y + (m.position.y - m.previous.y) * alpha + f64::from(m.height()) + 0.5,
|
||||
m.previous.z + (m.position.z - m.previous.z) * alpha,
|
||||
);
|
||||
if p.distance_squared(camera) >= 64.0 * 64.0 {
|
||||
// The name tag distance (64) is measured to the entity.
|
||||
let distance_sqr =
|
||||
glam::DVec3::new(m.position.x, m.position.y, m.position.z).distance_squared(camera);
|
||||
if distance_sqr >= 64.0 * 64.0 {
|
||||
continue;
|
||||
}
|
||||
let o = (p - camera).as_vec3();
|
||||
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
|
||||
// Text space: x right, y down (scale 0.025, -0.025).
|
||||
let at = |x: f32, y: f32| o + r * x - u * y;
|
||||
let width: f32 = name
|
||||
.chars()
|
||||
.map(|c| self.res.atlas.glyph(c).map_or(6.0, |g| g.1))
|
||||
.sum();
|
||||
let x0 = -(width / 2.0).trunc();
|
||||
let y0 = if name == "deadmau5" { -10.0 } else { 0.0 };
|
||||
let team = self.mob_team(m.id);
|
||||
// LivingEntityRenderer.shouldShowName (team rules included), then
|
||||
// MobRenderer: a visible name, or the mob under the crosshair.
|
||||
let invisible = sb::invisible_to(
|
||||
team,
|
||||
viewer,
|
||||
self.spectator(),
|
||||
m.has_effect("minecraft:invisibility"),
|
||||
);
|
||||
let view = sb::NameView {
|
||||
discrete: false,
|
||||
distance_sqr,
|
||||
invisible_to_viewer: invisible,
|
||||
hud_hidden: self.ui.hide_gui,
|
||||
is_camera: false,
|
||||
is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)),
|
||||
};
|
||||
if !sb::name_shown(team, viewer, view) || !(m.name_visible || Some(m.id) == target) {
|
||||
continue;
|
||||
}
|
||||
// getDisplayName: the custom name in the team's prefix, suffix and colour.
|
||||
let shown = match team {
|
||||
Some(t) => t.formatted_name(Text::literal(name)),
|
||||
None => Text::literal(name),
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
// EntityRenderer.extractNameTags: the score shows within the
|
||||
// below-name distance (10), under the name.
|
||||
let mut lift = 0.0;
|
||||
if distance_sqr < 10.0 * 10.0
|
||||
&& let Some(score) = self.below_name_text(m.id)
|
||||
{
|
||||
lines.push((score, 0.0));
|
||||
lift = f64::from(9.0f32 * 1.15 * 0.025);
|
||||
}
|
||||
lines.push((shown, lift));
|
||||
let l = self.world.light(
|
||||
m.position.x.floor() as i32,
|
||||
(m.position.y + f64::from(m.height())).floor() as i32,
|
||||
@@ -64,48 +115,77 @@ impl Game<'_> {
|
||||
);
|
||||
let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
|
||||
let away = forward.as_vec3() * 0.002;
|
||||
// `background`: unlit (vertex colour only) and a hair behind the text.
|
||||
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| {
|
||||
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
|
||||
let uvs = [
|
||||
[uv[0], uv[3]],
|
||||
[uv[2], uv[3]],
|
||||
[uv[2], uv[1]],
|
||||
[uv[0], uv[1]],
|
||||
];
|
||||
for ((x, y), uv) in corners.into_iter().zip(uvs) {
|
||||
out.push(Vertex {
|
||||
pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO })
|
||||
.to_array(),
|
||||
uv,
|
||||
layer: if background { 2 } else { 0 },
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
};
|
||||
// Background: Options.getBackgroundOpacity(0.25) black.
|
||||
quad(
|
||||
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
|
||||
[white.u0, white.v0, white.u1, white.v1],
|
||||
0x40_00_00_00,
|
||||
true,
|
||||
);
|
||||
let mut x = x0;
|
||||
for ch in name.chars() {
|
||||
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
|
||||
x += 6.0;
|
||||
continue;
|
||||
for (text, lift) in lines {
|
||||
let o = (p + glam::DVec3::new(0.0, lift, 0.0) - camera).as_vec3();
|
||||
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
|
||||
// Text space: x right, y down (scale 0.025, -0.025).
|
||||
let at = |x: f32, y: f32| o + r * x - u * y;
|
||||
let chars: Vec<(char, u32)> = text
|
||||
.spans
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
|
||||
// RGBA8, alpha in the top byte.
|
||||
let color = 0xFF00_0000
|
||||
| ((rgb & 0xFF) << 16)
|
||||
| (rgb & 0xFF00)
|
||||
| ((rgb >> 16) & 0xFF);
|
||||
s.text.chars().map(move |c| (c, color))
|
||||
})
|
||||
.collect();
|
||||
let width: f32 = chars
|
||||
.iter()
|
||||
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
|
||||
.sum();
|
||||
let x0 = -(width / 2.0).trunc();
|
||||
let y0 = if text.plain() == "deadmau5" {
|
||||
-10.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if ch != ' ' {
|
||||
quad(
|
||||
[x, y0, x + 8.0, y0 + 8.0],
|
||||
[g.u0, g.v0, g.u1, g.v1],
|
||||
0xFFFF_FFFF,
|
||||
false,
|
||||
);
|
||||
// `background`: unlit (vertex colour only) and a hair behind the text.
|
||||
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| {
|
||||
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
|
||||
let uvs = [
|
||||
[uv[0], uv[3]],
|
||||
[uv[2], uv[3]],
|
||||
[uv[2], uv[1]],
|
||||
[uv[0], uv[1]],
|
||||
];
|
||||
for ((x, y), uv) in corners.into_iter().zip(uvs) {
|
||||
out.push(Vertex {
|
||||
pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO })
|
||||
.to_array(),
|
||||
uv,
|
||||
layer: if background { 2 } else { 0 },
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
};
|
||||
// Background: Options.getBackgroundOpacity(0.25) black.
|
||||
quad(
|
||||
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
|
||||
[white.u0, white.v0, white.u1, white.v1],
|
||||
0x40_00_00_00,
|
||||
true,
|
||||
);
|
||||
let mut x = x0;
|
||||
for (ch, color) in chars {
|
||||
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
|
||||
x += 6.0;
|
||||
continue;
|
||||
};
|
||||
if ch != ' ' {
|
||||
quad(
|
||||
[x, y0, x + 8.0, y0 + 8.0],
|
||||
[g.u0, g.v0, g.u1, g.v1],
|
||||
color,
|
||||
false,
|
||||
);
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ use horizon_world::registry::BlockStateId;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The game level as natural spawning reads it.
|
||||
struct GameLevel<'g, 'a> {
|
||||
game: &'g Game<'a>,
|
||||
pub(super) struct GameLevel<'g, 'a> {
|
||||
pub(super) game: &'g Game<'a>,
|
||||
w: MobWorld<'g>,
|
||||
/// Boxes of the mobs this pass created, not yet in the game's list.
|
||||
pending: std::cell::RefCell<Vec<Aabb>>,
|
||||
@@ -194,7 +194,7 @@ impl NaturalLevel for GameLevel<'_, '_> {
|
||||
}
|
||||
}
|
||||
impl<'a> Game<'a> {
|
||||
fn natural_level(&self) -> GameLevel<'_, 'a> {
|
||||
pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> {
|
||||
GameLevel {
|
||||
game: self,
|
||||
w: self.mob_world_base(&[]),
|
||||
|
||||
@@ -477,14 +477,6 @@ impl Game<'_> {
|
||||
pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
||||
*self.persist.uuids.entry(id).or_insert_with(random_uuid)
|
||||
}
|
||||
/// The loaded mob with a saved UUID.
|
||||
pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
|
||||
self.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed))
|
||||
.map(|(id, _)| *id)
|
||||
}
|
||||
/// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`).
|
||||
fn state_from_nbt(&self, tag: &Tag) -> Option<BlockStateId> {
|
||||
let registry = self.res.assets.registry;
|
||||
|
||||
@@ -287,7 +287,15 @@ impl Game<'_> {
|
||||
// LivingEntity.die → removeAllEffects.
|
||||
self.potions.effects.clear();
|
||||
}
|
||||
for action in self.potions.effects.tick() {
|
||||
// The omens act from inside the effect tick (BadOmenMobEffect,
|
||||
// RaidOmenMobEffect).
|
||||
let mut effects = std::mem::take(&mut self.potions.effects);
|
||||
let (actions, raid_omen_added) = effects.tick_with(&mut |e| self.omen_tick(e));
|
||||
self.potions.effects = effects;
|
||||
if raid_omen_added {
|
||||
self.raid_omen_added();
|
||||
}
|
||||
for action in actions {
|
||||
self.apply_effect_action(action);
|
||||
}
|
||||
let modifiers = self.potions.effects.modifiers();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,8 @@ use horizon_client::{
|
||||
containers::{BlockEntity, FurnaceKind},
|
||||
hud::{HudBatch, Rect, rgba},
|
||||
items::ItemStack,
|
||||
recipe_book::{Available, Book, BookType, Collection, Display, Entry, Tab},
|
||||
menu::place::{PostPlace, Stacked},
|
||||
recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab},
|
||||
ui::EditBox,
|
||||
};
|
||||
use std::{
|
||||
@@ -71,6 +72,11 @@ pub(super) struct RecipeUi {
|
||||
/// Squeeze animations of new recipes: ticks left per button index and tab.
|
||||
button_anim: Vec<(usize, f32)>,
|
||||
tab_anim: Vec<(Tab, f32)>,
|
||||
/// The client's copy of the known recipes (`ClientRecipeBook`), its
|
||||
/// order deciding the buttons', and the recipes it was last synced with.
|
||||
client: ClientBook,
|
||||
client_known: Option<BTreeSet<String>>,
|
||||
client_version: u64,
|
||||
}
|
||||
|
||||
impl RecipeUi {
|
||||
@@ -182,11 +188,6 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.ensure_book();
|
||||
for id in recipes {
|
||||
if !self.level.recipe_book.to_be_displayed.contains(id) {
|
||||
self.level.recipe_book.to_be_displayed.push(id.clone());
|
||||
}
|
||||
}
|
||||
let icon = self
|
||||
.recipe_ui
|
||||
.book
|
||||
@@ -212,42 +213,55 @@ impl Game<'_> {
|
||||
fn book_grid(&self) -> (usize, usize) {
|
||||
(self.craft_size, self.craft_size)
|
||||
}
|
||||
/// The slot ids holding the menu's recipe inputs (and, for furnaces, the
|
||||
/// fuel and result slots that the book also reads).
|
||||
fn book_input_slots(&self, book: BookType) -> Vec<usize> {
|
||||
match book {
|
||||
BookType::Crafting => {
|
||||
let (w, h) = self.book_grid();
|
||||
(0..w * h).map(|i| 100 + i).collect()
|
||||
}
|
||||
_ => vec![300],
|
||||
}
|
||||
/// The items the book counts (`RecipeBookComponent.updateStackedContents`):
|
||||
/// the inventory and the menu's crafting slots, as the menu engine counts them.
|
||||
fn book_available(&mut self, _book: BookType) -> Stacked {
|
||||
let mut out = Stacked::default();
|
||||
let stock = &mut out;
|
||||
self.menu_session(|menu, env, _| {
|
||||
*stock = menu.stacked_contents(env);
|
||||
Some(false)
|
||||
});
|
||||
out
|
||||
}
|
||||
/// The items the book counts: the inventory and the menu's crafting slots.
|
||||
fn book_available(&mut self, book: BookType) -> Available {
|
||||
let mut stacks: Vec<ItemStack> = self.inventory.iter().flatten().cloned().collect();
|
||||
let slots = match book {
|
||||
BookType::Crafting => self.book_input_slots(book),
|
||||
_ => vec![300, 301, 302],
|
||||
};
|
||||
for slot in slots {
|
||||
if let Some(s) = self.slot_mut(slot).clone() {
|
||||
stacks.push(s);
|
||||
/// Sends the client book what changed in the server's: the first time a
|
||||
/// replacing batch (vanilla's server iterates an identity hash set; this
|
||||
/// one goes in id order), then each unlock and removal.
|
||||
fn sync_client_book(&mut self) {
|
||||
let known = &self.level.recipe_book.recipes;
|
||||
let index = &self.res.stations.recipe_index;
|
||||
let ui = &mut self.recipe_ui;
|
||||
match ui.client_known.as_ref() {
|
||||
Some(previous) if previous == known => return,
|
||||
Some(previous) => {
|
||||
for id in previous.difference(known) {
|
||||
for d in index.display_ids(id) {
|
||||
ui.client.remove(d);
|
||||
}
|
||||
}
|
||||
for id in known.difference(previous) {
|
||||
for d in index.display_ids(id) {
|
||||
ui.client.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.client.clear();
|
||||
for id in known {
|
||||
for d in index.display_ids(id) {
|
||||
ui.client.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Available::from_stacks(stacks.iter())
|
||||
}
|
||||
fn unlocked_recipes(&self) -> BTreeSet<String> {
|
||||
self.adv
|
||||
.recipes
|
||||
.iter()
|
||||
.chain(self.level.recipe_book.recipes.iter())
|
||||
.cloned()
|
||||
.collect()
|
||||
ui.client_known = Some(known.clone());
|
||||
ui.client_version += 1;
|
||||
}
|
||||
fn ensure_book(&mut self) {
|
||||
if self.recipe_ui.book.is_none() {
|
||||
self.recipe_ui.book = Some(Book::build(&self.res.recipes, &self.res.items));
|
||||
let mut book = Book::build(&self.res.recipes, &self.res.items);
|
||||
book.set_display_ids(&self.res.stations.recipe_index);
|
||||
self.recipe_ui.book = Some(book);
|
||||
}
|
||||
if self.recipe_ui.search.is_none() {
|
||||
let mut search = EditBox::new(0.0, 0.0, 81.0, 14.0);
|
||||
@@ -260,6 +274,7 @@ impl Game<'_> {
|
||||
/// Rebuilds the tab and button lists when anything they depend on changed.
|
||||
fn refresh_book_view(&mut self, book_type: BookType) {
|
||||
self.ensure_book();
|
||||
self.sync_client_book();
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
for s in self.inventory.iter().flatten() {
|
||||
(&s.item, s.count, s.damage).hash(&mut h);
|
||||
@@ -276,8 +291,7 @@ impl Game<'_> {
|
||||
stack.map(|s| (s.item, s.count)).hash(&mut h);
|
||||
}
|
||||
self.craft_size.hash(&mut h);
|
||||
self.adv.recipes.len().hash(&mut h);
|
||||
self.level.recipe_book.recipes.len().hash(&mut h);
|
||||
self.recipe_ui.client_version.hash(&mut h);
|
||||
self.book_filtering(book_type).hash(&mut h);
|
||||
self.recipe_ui.tab.map(|t| format!("{t:?}")).hash(&mut h);
|
||||
self.recipe_ui
|
||||
@@ -311,13 +325,12 @@ impl Game<'_> {
|
||||
let Some(book) = self.recipe_ui.book.take() else {
|
||||
return;
|
||||
};
|
||||
let unlocked = self.unlocked_recipes();
|
||||
let filtering = self.book_filtering(book_type);
|
||||
let (gw, gh) = self.book_grid();
|
||||
let available = self.book_available(book_type);
|
||||
let shown = |e: &Entry| {
|
||||
(book_type != BookType::Crafting || e.fits(gw, gh))
|
||||
&& (!filtering || available.can_craft(&e.requirements()))
|
||||
&& (!filtering || book.can_craft(e, &available))
|
||||
};
|
||||
let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id);
|
||||
let mut tabs = Vec::new();
|
||||
@@ -325,8 +338,10 @@ impl Game<'_> {
|
||||
if tab == Tab::Search {
|
||||
continue;
|
||||
}
|
||||
let hit = book
|
||||
.collections(&unlocked, book_type, tab)
|
||||
let hit = self
|
||||
.recipe_ui
|
||||
.client
|
||||
.collections(&book, book_type, tab)
|
||||
.iter()
|
||||
.flat_map(|c| c.entries.iter())
|
||||
.any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i]));
|
||||
@@ -369,20 +384,20 @@ impl Game<'_> {
|
||||
let Some(book) = ui.book.as_ref() else {
|
||||
return View::default();
|
||||
};
|
||||
let unlocked = self.unlocked_recipes();
|
||||
let available = self.book_available(book_type);
|
||||
let (gw, gh) = self.book_grid();
|
||||
let selected = |e: &Entry| match book_type {
|
||||
BookType::Crafting => e.fits(gw, gh),
|
||||
_ => true,
|
||||
};
|
||||
let craftable = |e: &Entry| selected(e) && available.can_craft(&e.requirements());
|
||||
let craftable = |e: &Entry| selected(e) && book.can_craft(e, &available);
|
||||
let filtering = self.book_filtering(book_type);
|
||||
let mut tabs = Vec::new();
|
||||
for tab in book_type.tabs() {
|
||||
let visible = tab == Tab::Search
|
||||
|| book
|
||||
.collections(&unlocked, book_type, tab)
|
||||
|| ui
|
||||
.client
|
||||
.collections(book, book_type, tab)
|
||||
.iter()
|
||||
.any(|c| c.entries.iter().any(|&i| selected(&book.entries[i])));
|
||||
if visible {
|
||||
@@ -395,7 +410,7 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.map(|s| s.value.clone())
|
||||
.unwrap_or_default();
|
||||
let collections: Vec<Collection> = book.collections(&unlocked, book_type, tab);
|
||||
let collections: Vec<Collection> = ui.client.collections(book, book_type, tab);
|
||||
let mut buttons = Vec::new();
|
||||
for c in collections {
|
||||
if !c.entries.iter().any(|&i| selected(&book.entries[i])) {
|
||||
@@ -660,8 +675,9 @@ impl Game<'_> {
|
||||
self.recipe_ui.ghost.clear();
|
||||
self.place_recipe(book_type, entry_index, use_max);
|
||||
}
|
||||
/// `ServerPlaceRecipe.placeRecipe`: fills the grid from the inventory,
|
||||
/// or shows the ghost recipe when the items are missing.
|
||||
/// `ServerboundPlaceRecipePacket`: the server places the recipe
|
||||
/// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost
|
||||
/// recipe when the items are missing.
|
||||
fn place_recipe(&mut self, book_type: BookType, entry_index: usize, use_max: bool) {
|
||||
let Some(entry) = self
|
||||
.recipe_ui
|
||||
@@ -672,88 +688,23 @@ impl Game<'_> {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (gw, gh) = match book_type {
|
||||
BookType::Crafting => self.book_grid(),
|
||||
_ => (1, 1),
|
||||
};
|
||||
let inputs = self.book_input_slots(book_type);
|
||||
let clear: Vec<usize> = match book_type {
|
||||
BookType::Crafting => inputs.clone(),
|
||||
_ => vec![300, 302],
|
||||
};
|
||||
if !self.creative && !self.can_clear_grid(&clear) {
|
||||
return;
|
||||
}
|
||||
let available = self.book_available(book_type);
|
||||
let requirements = entry.requirements();
|
||||
if !available.can_craft(&requirements) {
|
||||
self.clear_book_grid(&clear);
|
||||
let creative = self.creative;
|
||||
let mut post = None;
|
||||
let answer = &mut post;
|
||||
self.menu_session(|menu, env, _| {
|
||||
// handlePlaceRecipe: an impossible recipe is refused outright.
|
||||
if env
|
||||
.recipes
|
||||
.placement(&entry.id)
|
||||
.is_none_or(|p| p.impossible())
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
*answer = Some(menu.place_recipe(env, &entry.id, use_max, creative, None));
|
||||
Some(true)
|
||||
});
|
||||
if post == Some(PostPlace::Ghost) {
|
||||
self.fill_ghost(book_type, &entry);
|
||||
self.recipe_book_changed();
|
||||
return;
|
||||
}
|
||||
let matches_placed = self.recipe_matches(book_type, &entry);
|
||||
let biggest = available.biggest_stack(&requirements);
|
||||
if matches_placed {
|
||||
for slot in &inputs {
|
||||
let stack = self.slot_mut(*slot).clone();
|
||||
if let Some(s) = stack {
|
||||
let max = self.res.items.get(&s.item).map_or(64, |i| i.max_stack);
|
||||
if biggest.min(max) < s.count + 1 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let amount = if use_max {
|
||||
biggest
|
||||
} else if matches_placed {
|
||||
let smallest = inputs
|
||||
.iter()
|
||||
.filter_map(|slot| self.slot_mut(*slot).as_ref().map(|s| s.count))
|
||||
.min();
|
||||
smallest.map_or(1, |n| n + 1)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let order = self
|
||||
.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.map(|b| b.order.clone())
|
||||
.unwrap_or_default();
|
||||
let Some(mut used) = available.pick(&requirements, amount, &order) else {
|
||||
return;
|
||||
};
|
||||
let item_max = |item: &str| self.res.items.get(item).map_or(64, |i| i.max_stack);
|
||||
let mut amount = amount;
|
||||
let clamped = used.iter().map(|i| item_max(i)).fold(amount, u32::min);
|
||||
if clamped != amount {
|
||||
amount = clamped;
|
||||
match available.pick(&requirements, amount, &order) {
|
||||
Some(u) => used = u,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
self.clear_book_grid(&clear);
|
||||
for (ingredient, grid_index) in entry.grid_cells(gw, gh) {
|
||||
let Some(ingredient) = ingredient else {
|
||||
continue;
|
||||
};
|
||||
let slot = inputs[grid_index.min(inputs.len() - 1)];
|
||||
let mut remaining = amount as i64;
|
||||
while remaining > 0 {
|
||||
remaining = self.move_item_to_grid(slot, &used[ingredient], remaining);
|
||||
if remaining < 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(BlockEntity::Furnace(f)) = self
|
||||
.container
|
||||
.and_then(|k| self.world.block_entities.get_mut(&k))
|
||||
{
|
||||
f.cooking_timer = 0;
|
||||
}
|
||||
self.recipe_book_changed();
|
||||
}
|
||||
@@ -764,111 +715,6 @@ impl Game<'_> {
|
||||
self.container_changed(key);
|
||||
}
|
||||
}
|
||||
/// `menu.recipeMatches(recipe)`: the grid already holds this recipe.
|
||||
fn recipe_matches(&mut self, book_type: BookType, entry: &Entry) -> bool {
|
||||
match (&entry.display, book_type) {
|
||||
(Display::Furnace(ingredient), _) => self
|
||||
.slot_mut(300)
|
||||
.as_ref()
|
||||
.is_some_and(|s| ingredient.test(s)),
|
||||
(_, BookType::Crafting) => {
|
||||
let n = self.craft_size;
|
||||
let grid: Vec<Option<ItemStack>> =
|
||||
(0..n * n).map(|i| self.craft_grid[i].clone()).collect();
|
||||
self.res
|
||||
.recipes
|
||||
.find(&grid, n)
|
||||
.is_some_and(|(name, _)| format!("minecraft:{name}") == entry.id)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// `Inventory.getSlotWithRemainingSpace`.
|
||||
fn has_room_for(&self, stack: &ItemStack) -> bool {
|
||||
let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack);
|
||||
self.inventory
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|s| s.same_item_same_components(stack) && max > 1 && s.count < max)
|
||||
}
|
||||
/// `ServerPlaceRecipe.testClearGrid`.
|
||||
fn can_clear_grid(&mut self, slots: &[usize]) -> bool {
|
||||
let mut free: Vec<ItemStack> = Vec::new();
|
||||
let free_in_inventory = self.inventory.iter().filter(|s| s.is_none()).count();
|
||||
for &slot in slots {
|
||||
let Some(mut stack) = self.slot_mut(slot).clone() else {
|
||||
continue;
|
||||
};
|
||||
if !self.has_room_for(&stack) && free.len() <= free_in_inventory {
|
||||
for other in free.iter_mut() {
|
||||
let max = self.res.items.get(&other.item).map_or(64, |i| i.max_stack);
|
||||
if other.item == stack.item
|
||||
&& other.count != max
|
||||
&& other.count + stack.count <= max
|
||||
{
|
||||
other.count += stack.count;
|
||||
stack.count = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if stack.count > 0 {
|
||||
if free.len() >= free_in_inventory {
|
||||
return false;
|
||||
}
|
||||
free.push(stack);
|
||||
}
|
||||
} else if !self.has_room_for(&stack) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `ServerPlaceRecipe.clearGrid`: the grid's items go back to the inventory.
|
||||
fn clear_book_grid(&mut self, slots: &[usize]) {
|
||||
for &slot in slots {
|
||||
if let Some(stack) = self.slot_mut(slot).take() {
|
||||
self.give_or_drop_quiet(stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Back into the inventory; what does not fit is lost only in creative
|
||||
/// (survival checks room first with `can_clear_grid`).
|
||||
fn give_or_drop_quiet(&mut self, stack: ItemStack) {
|
||||
let _ = self.give(stack);
|
||||
}
|
||||
/// `ServerPlaceRecipe.moveItemToGrid`; the count still to move or -1.
|
||||
fn move_item_to_grid(&mut self, slot: usize, item: &str, count: i64) -> i64 {
|
||||
let target = self.slot_mut(slot).clone();
|
||||
let found = self.inventory.iter().position(|s| {
|
||||
s.as_ref().is_some_and(|s| {
|
||||
&*s.item == item
|
||||
&& s.damage == 0
|
||||
&& s.enchantments().is_empty()
|
||||
&& s.custom_name().is_none()
|
||||
&& target
|
||||
.as_ref()
|
||||
.is_none_or(|t| t.same_item_same_components(s))
|
||||
})
|
||||
});
|
||||
let Some(index) = found else { return -1 };
|
||||
let Some(source) = self.inventory[index].as_mut() else {
|
||||
return -1;
|
||||
};
|
||||
let taken = (count as u32).min(source.count);
|
||||
let moved = ItemStack {
|
||||
count: taken,
|
||||
..source.clone()
|
||||
};
|
||||
source.count -= taken;
|
||||
if source.count == 0 {
|
||||
self.inventory[index] = None;
|
||||
}
|
||||
match self.slot_mut(slot) {
|
||||
Some(existing) => existing.count += taken,
|
||||
empty => *empty = Some(moved),
|
||||
}
|
||||
count - i64::from(taken)
|
||||
}
|
||||
|
||||
// ---- ghost recipe ----
|
||||
|
||||
|
||||
@@ -102,6 +102,16 @@ pub(super) struct Remote {
|
||||
pub chat_input: Option<String>,
|
||||
action_bar: Option<(String, Instant)>,
|
||||
players: HashMap<u128, String>,
|
||||
/// `ClientPacketListener.playerInfoMap` as player-list entries, and
|
||||
/// which of them are listed.
|
||||
tab_players: HashMap<u128, horizon_client::tab_list::TabPlayer>,
|
||||
listed: std::collections::HashSet<u128>,
|
||||
/// `ClientboundLoginPacket.onlineMode`: the player list shows heads.
|
||||
online_mode: bool,
|
||||
/// Player entities in the level: entity id to profile UUID.
|
||||
level_players: HashMap<i32, u128>,
|
||||
/// The local player's profile UUID (always in the level).
|
||||
profile: u128,
|
||||
destroying: Option<([i32; 3], u8, f32)>,
|
||||
destroy_delay: u32,
|
||||
placing: Option<([i32; 3], u64)>,
|
||||
@@ -126,6 +136,16 @@ fn face_direction(face: [i32; 3]) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A protocol number format as the scoreboard's.
|
||||
fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFormat {
|
||||
use horizon_client::scoreboard::{NumberFormat, tag_to_json};
|
||||
match f {
|
||||
play::NumberFormat::Blank => NumberFormat::Blank,
|
||||
play::NumberFormat::Styled(t) => NumberFormat::Styled(tag_to_json(t)),
|
||||
play::NumberFormat::Fixed(t) => NumberFormat::Fixed(tag_to_json(t)),
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
|
||||
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
|
||||
@@ -213,6 +233,11 @@ impl Game<'_> {
|
||||
chat_input: None,
|
||||
action_bar: None,
|
||||
players: HashMap::new(),
|
||||
tab_players: HashMap::new(),
|
||||
listed: Default::default(),
|
||||
online_mode: false,
|
||||
level_players: HashMap::new(),
|
||||
profile: 0,
|
||||
destroying: None,
|
||||
destroy_delay: 0,
|
||||
placing: None,
|
||||
@@ -231,6 +256,8 @@ impl Game<'_> {
|
||||
if let Some(mut r) = self.remote.take() {
|
||||
r.session.disconnect();
|
||||
}
|
||||
self.tab_list.reset();
|
||||
self.score.board = Default::default();
|
||||
self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1);
|
||||
self.streaming.paused = true;
|
||||
self.world = World::new(self.res.facts.air, 0);
|
||||
@@ -238,6 +265,9 @@ impl Game<'_> {
|
||||
self.mobs.clear();
|
||||
self.dropped.clear();
|
||||
self.particles.clear();
|
||||
self.score.board = Default::default();
|
||||
self.tab_list = Default::default();
|
||||
self.border = Default::default();
|
||||
self.screen = Screen::Playing;
|
||||
self.container = None;
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
@@ -323,11 +353,14 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Event::Joined {
|
||||
registries, name, ..
|
||||
registries,
|
||||
name,
|
||||
uuid,
|
||||
} => {
|
||||
self.set_registries(registries);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.joined = true;
|
||||
r.profile = uuid;
|
||||
r.status = format!("Joined as {name}; loading terrain...");
|
||||
}
|
||||
}
|
||||
@@ -662,6 +695,7 @@ impl Game<'_> {
|
||||
match packet {
|
||||
C::Login(p) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.online_mode = p.online_mode;
|
||||
r.entity_id = p.player_id;
|
||||
r.view_distance = p.chunk_radius;
|
||||
}
|
||||
@@ -797,10 +831,20 @@ impl Game<'_> {
|
||||
.unwrap_or_default();
|
||||
let yaw = horizon_protocol::buf::unpack_degrees(p.yaw);
|
||||
let head = horizon_protocol::buf::unpack_degrees(p.head_yaw);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
if kind == "minecraft:player" {
|
||||
r.level_players.insert(p.id, p.uuid);
|
||||
} else {
|
||||
r.level_players.remove(&p.id);
|
||||
}
|
||||
}
|
||||
self.spawn_entity(p.id, &kind, p.position, yaw, head);
|
||||
}
|
||||
C::RemoveEntities(p) => {
|
||||
for id in p.ids {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.level_players.remove(&id);
|
||||
}
|
||||
self.remove_entity(id);
|
||||
}
|
||||
}
|
||||
@@ -1068,7 +1112,45 @@ impl Game<'_> {
|
||||
}
|
||||
C::PlayerInfoUpdate(p) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
// handlePlayerInfoUpdate: new entries first, then every
|
||||
// action on every known entry.
|
||||
if p.actions & 1 != 0 {
|
||||
for e in &p.entries {
|
||||
if let Some(name) = &e.name {
|
||||
r.tab_players.entry(e.uuid).or_insert_with(|| {
|
||||
horizon_client::tab_list::TabPlayer::new(e.uuid, name.clone())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for e in p.entries {
|
||||
if let Some(t) = r.tab_players.get_mut(&e.uuid) {
|
||||
if let Some(mode) = e.game_mode {
|
||||
t.game_mode = mode;
|
||||
}
|
||||
if let Some(latency) = e.latency {
|
||||
t.latency = latency;
|
||||
}
|
||||
if let Some(name) = &e.display_name {
|
||||
t.display_name =
|
||||
name.as_ref().map(horizon_client::scoreboard::tag_to_json);
|
||||
}
|
||||
if let Some(order) = e.list_order {
|
||||
t.list_order = order;
|
||||
}
|
||||
if let Some(hat) = e.show_hat {
|
||||
t.show_hat = hat;
|
||||
}
|
||||
match e.listed {
|
||||
Some(true) => {
|
||||
r.listed.insert(e.uuid);
|
||||
}
|
||||
Some(false) => {
|
||||
r.listed.remove(&e.uuid);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some(name) = e.name {
|
||||
r.players.insert(e.uuid, name);
|
||||
}
|
||||
@@ -1079,9 +1161,74 @@ impl Game<'_> {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
for u in p.uuids {
|
||||
r.players.remove(&u);
|
||||
r.tab_players.remove(&u);
|
||||
r.listed.remove(&u);
|
||||
}
|
||||
}
|
||||
}
|
||||
C::TabList(p) => {
|
||||
// handleTabListCustomisation: empty text clears it.
|
||||
let text = |t: &Tag| {
|
||||
let json = horizon_client::scoreboard::tag_to_json(t);
|
||||
let text = horizon_client::scoreboard::comp_text(&json);
|
||||
(!text.plain().is_empty()).then_some(text)
|
||||
};
|
||||
self.tab_list.header = text(&p.header);
|
||||
self.tab_list.footer = text(&p.footer);
|
||||
}
|
||||
C::InitializeBorder(p) => {
|
||||
let b = &mut self.border;
|
||||
b.set_center([p.center_x, p.center_z]);
|
||||
if p.lerp_time > 0 {
|
||||
b.lerp_between(p.old_size, p.new_size, p.lerp_time);
|
||||
} else {
|
||||
b.set_size(p.new_size);
|
||||
}
|
||||
b.set_absolute_max_size(p.absolute_max_size);
|
||||
b.warning_distance = p.warning_blocks;
|
||||
b.warning_time = p.warning_time;
|
||||
}
|
||||
C::SetBorderCenter(p) => self.border.set_center([p.x, p.z]),
|
||||
C::SetBorderLerpSize(p) => {
|
||||
self.border
|
||||
.lerp_between(p.old_size, p.new_size, p.lerp_time)
|
||||
}
|
||||
C::SetBorderSize(p) => self.border.set_size(p.size),
|
||||
C::SetBorderWarningDelay(p) => self.border.warning_time = p.delay,
|
||||
C::SetBorderWarningDistance(p) => self.border.warning_distance = p.blocks,
|
||||
C::SetObjective(p) => self.remote_objective(p),
|
||||
C::SetDisplayObjective(p) => {
|
||||
// DisplaySlot ids: list, sidebar, below_name, then the team sidebars.
|
||||
let slot = match p.slot {
|
||||
0 => "list".to_owned(),
|
||||
2 => "below_name".to_owned(),
|
||||
n @ 3..=18 => format!(
|
||||
"sidebar.team.{}",
|
||||
horizon_client::text::COLORS[(n - 3) as usize].1
|
||||
),
|
||||
_ => "sidebar".to_owned(),
|
||||
};
|
||||
let board = &mut self.score.board;
|
||||
let objective = board.objective(&p.objective).map(|o| o.name.clone());
|
||||
board.set_display_objective(&slot, objective.as_deref());
|
||||
}
|
||||
C::SetScore(p) => {
|
||||
let board = &mut self.score.board;
|
||||
if board.objective(&p.objective).is_some() {
|
||||
let s = board.score_mut(&p.owner, &p.objective);
|
||||
s.value = p.score;
|
||||
s.display = p
|
||||
.display
|
||||
.as_ref()
|
||||
.map(horizon_client::scoreboard::tag_to_json);
|
||||
s.number_format = p.number_format.as_ref().map(number_format);
|
||||
}
|
||||
}
|
||||
C::ResetScore(p) => match &p.objective {
|
||||
Some(o) => self.score.board.reset_one(&p.owner, o),
|
||||
None => self.score.board.reset_all(&p.owner),
|
||||
},
|
||||
C::SetPlayerTeam(p) => self.remote_team(p),
|
||||
C::SetChunkCacheRadius(p) => {
|
||||
self.streaming.radius = self.settings.render_distance.min(p.distance + 1).max(2);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
@@ -1103,6 +1250,104 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `handleAddObjective`: add, remove or change an objective.
|
||||
fn remote_objective(&mut self, p: play::SetObjective) {
|
||||
use horizon_client::scoreboard::{RenderType, tag_to_json};
|
||||
let board = &mut self.score.board;
|
||||
match (p.method, p.display) {
|
||||
(1, _) => board.remove_objective(&p.name),
|
||||
(method, Some((name, render, format))) => {
|
||||
let render = if render == 1 {
|
||||
RenderType::Hearts
|
||||
} else {
|
||||
RenderType::Integer
|
||||
};
|
||||
let format = format.as_ref().map(number_format);
|
||||
if method == 0 {
|
||||
board.add_objective(
|
||||
&p.name,
|
||||
"dummy",
|
||||
tag_to_json(&name),
|
||||
render,
|
||||
false,
|
||||
format,
|
||||
);
|
||||
} else if let Some(o) = board.objective_mut(&p.name) {
|
||||
o.display_name = tag_to_json(&name);
|
||||
o.render_type = render;
|
||||
o.number_format = format;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// `handleSetPlayerTeamPacket`.
|
||||
fn remote_team(&mut self, p: play::SetPlayerTeam) {
|
||||
use horizon_client::scoreboard::{CollisionRule, Visibility, tag_to_json};
|
||||
let board = &mut self.score.board;
|
||||
if p.method == 1 {
|
||||
board.remove_team(&p.name);
|
||||
return;
|
||||
}
|
||||
if p.method == 0 {
|
||||
board.add_team(&p.name);
|
||||
}
|
||||
if let Some(params) = &p.parameters
|
||||
&& let Some(team) = board.team_mut(&p.name)
|
||||
{
|
||||
team.display_name = tag_to_json(¶ms.display_name);
|
||||
team.prefix = tag_to_json(¶ms.prefix);
|
||||
team.suffix = tag_to_json(¶ms.suffix);
|
||||
team.color = params
|
||||
.color
|
||||
.and_then(|c| horizon_client::text::COLORS.get(c as usize))
|
||||
.map(|c| c.1.to_owned());
|
||||
team.allow_friendly_fire = params.options & 1 != 0;
|
||||
team.see_friendly_invisibles = params.options & 2 != 0;
|
||||
team.nametag_visibility = Visibility::ALL
|
||||
.get(params.name_tag_visibility as usize)
|
||||
.copied()
|
||||
.unwrap_or(Visibility::Always);
|
||||
team.collision_rule = CollisionRule::ALL
|
||||
.get(params.collision_rule as usize)
|
||||
.copied()
|
||||
.unwrap_or(CollisionRule::Always);
|
||||
}
|
||||
match p.method {
|
||||
0 | 3 => {
|
||||
for player in &p.players {
|
||||
board.add_to_team(player, &p.name);
|
||||
}
|
||||
}
|
||||
4 => {
|
||||
for player in &p.players {
|
||||
board.remove_from_team(player);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// The player list's view of the connection: the listed players, online
|
||||
/// mode, and which players are in the level with an upside-down name.
|
||||
pub(super) fn remote_tab_players(
|
||||
&self,
|
||||
) -> Option<(Vec<horizon_client::tab_list::TabPlayer>, bool, Vec<u128>)> {
|
||||
let r = self.remote.as_ref()?;
|
||||
let players: Vec<_> = r
|
||||
.listed
|
||||
.iter()
|
||||
.filter_map(|u| r.tab_players.get(u).cloned())
|
||||
.collect();
|
||||
let upside_down = players
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
(p.name == "Dinnerbone" || p.name == "Grumm")
|
||||
&& (p.uuid == r.profile || r.level_players.values().any(|u| *u == p.uuid))
|
||||
})
|
||||
.map(|p| p.uuid)
|
||||
.collect();
|
||||
Some((players, r.online_mode, upside_down))
|
||||
}
|
||||
/// ChatType decoration: `chat.translation_key` with sender/content parameters.
|
||||
fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String {
|
||||
let Some(r) = self.remote.as_ref() else {
|
||||
@@ -1266,6 +1511,8 @@ impl Game<'_> {
|
||||
if self.use_delay > 0 {
|
||||
self.use_delay -= 1;
|
||||
}
|
||||
// ClientLevel.tick: the border's size change.
|
||||
self.border.tick();
|
||||
self.tick_remote_entities();
|
||||
self.tick_hand();
|
||||
self.tick_particles();
|
||||
|
||||
@@ -147,10 +147,10 @@ impl Game<'_> {
|
||||
// drawn on the HUD by draw_spyglass.
|
||||
let fx = &self.res.screen_fx;
|
||||
let overlays = hud_overlays::CameraOverlays {
|
||||
vignette: self
|
||||
.settings
|
||||
.vignette
|
||||
.then_some((fx.vignette_brightness, 0.0)),
|
||||
vignette: self.settings.vignette.then_some((
|
||||
fx.vignette_brightness,
|
||||
self.border.warning_strength(p.position.x, p.position.z),
|
||||
)),
|
||||
first_person: self.camera_type.first_person(),
|
||||
scoping: self.scoping(),
|
||||
game_time_delta: 0.0,
|
||||
|
||||
@@ -21,7 +21,8 @@ use std::collections::HashSet;
|
||||
/// What `ServerPlayer` last recorded for the criteria that follow the player.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recorded {
|
||||
health: Option<i32>,
|
||||
/// `lastRecordedHealthAndAbsorption` (compared as a float).
|
||||
health_and_absorption: Option<f32>,
|
||||
food: Option<i32>,
|
||||
air: Option<i32>,
|
||||
armor: Option<i32>,
|
||||
@@ -314,18 +315,29 @@ impl Game<'_> {
|
||||
});
|
||||
}
|
||||
}
|
||||
let display = self.player_display_comp();
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
let health = (p.health.health() + p.health.absorption()).ceil() as i32;
|
||||
let health_and_absorption = p.health.health() + p.health.absorption();
|
||||
let food = p.health.food.food;
|
||||
// getArmorValue: the armor attribute rounded down.
|
||||
let armor = p
|
||||
.attribute("minecraft:armor")
|
||||
.or_else(|_| p.attribute("armor"))
|
||||
.unwrap_or(0.0)
|
||||
.ceil() as i32;
|
||||
.floor() as i32;
|
||||
let rec = &mut self.score.recorded;
|
||||
let board = &mut self.score.board;
|
||||
if rec.health_and_absorption != Some(health_and_absorption) {
|
||||
rec.health_and_absorption = Some(health_and_absorption);
|
||||
let value = health_and_absorption.ceil() as i32;
|
||||
board.for_all_objectives_with(
|
||||
sb::CRITERIA_HEALTH,
|
||||
PLAYER_NAME,
|
||||
Some(&display),
|
||||
|_| value,
|
||||
);
|
||||
}
|
||||
for (criteria, last, value) in [
|
||||
(sb::CRITERIA_HEALTH, &mut rec.health, health),
|
||||
(sb::CRITERIA_FOOD, &mut rec.food, food),
|
||||
// The air supply is full unless the player is drowning.
|
||||
(sb::CRITERIA_AIR, &mut rec.air, 300),
|
||||
@@ -335,7 +347,12 @@ impl Game<'_> {
|
||||
] {
|
||||
if *last != Some(value) {
|
||||
*last = Some(value);
|
||||
board.for_all_objectives(criteria, PLAYER_NAME, |_| value);
|
||||
board.for_all_objectives_with(
|
||||
criteria,
|
||||
PLAYER_NAME,
|
||||
Some(&display),
|
||||
|_| value,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,29 +363,39 @@ impl Game<'_> {
|
||||
}
|
||||
/// `ServerPlayer.die`: the death count.
|
||||
pub(super) fn score_player_died(&mut self) {
|
||||
let display = self.player_display_comp();
|
||||
let board = &mut self.score.board;
|
||||
board.for_all_objectives(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, |v| v + 1);
|
||||
board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, Some(&display), |v| {
|
||||
v.wrapping_add(1)
|
||||
});
|
||||
// A respawned player has everything to record again.
|
||||
self.score.recorded = Recorded::default();
|
||||
}
|
||||
/// `ServerPlayer.awardKillScore`: total kills and the team kill counts.
|
||||
pub(super) fn score_player_killed(&mut self, victim: Target) {
|
||||
let victim_name = self.holder_name(victim);
|
||||
let display = self.player_display_comp();
|
||||
let board = &mut self.score.board;
|
||||
board.for_all_objectives(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, |v| v + 1);
|
||||
let inc = |v: i32| v.wrapping_add(1);
|
||||
board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, Some(&display), inc);
|
||||
if victim == Target::Player {
|
||||
board.for_all_objectives(sb::CRITERIA_PLAYER_KILLS, PLAYER_NAME, |v| v + 1);
|
||||
board.for_all_objectives_with(
|
||||
sb::CRITERIA_PLAYER_KILLS,
|
||||
PLAYER_NAME,
|
||||
Some(&display),
|
||||
inc,
|
||||
);
|
||||
}
|
||||
let color_of =
|
||||
|board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone());
|
||||
if let Some(victim_name) = victim_name {
|
||||
if let Some(color) = color_of(board, &victim_name) {
|
||||
let criteria = format!("teamkill.{color}");
|
||||
board.for_all_objectives(&criteria, PLAYER_NAME, |v| v + 1);
|
||||
board.for_all_objectives_with(&criteria, PLAYER_NAME, Some(&display), inc);
|
||||
}
|
||||
if let Some(color) = color_of(board, PLAYER_NAME) {
|
||||
let criteria = format!("killedByTeam.{color}");
|
||||
board.for_all_objectives(&criteria, &victim_name, |v| v + 1);
|
||||
board.for_all_objectives(&criteria, &victim_name, inc);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -377,9 +404,62 @@ impl Game<'_> {
|
||||
let Some(uuid) = self.persist.uuids.get(&id).copied() else {
|
||||
return;
|
||||
};
|
||||
let name = uuid_text(uuid);
|
||||
self.score.board.reset_all(&name);
|
||||
self.score.board.remove_from_team(&name);
|
||||
self.score.board.entity_removed(&uuid_text(uuid));
|
||||
}
|
||||
|
||||
// ---- teams in gameplay -----------------------------------------------------
|
||||
|
||||
/// `Entity.getTeam` of a mob (a mob joins a team by its UUID).
|
||||
pub(super) fn mob_team(&self, id: u32) -> Option<&sb::Team> {
|
||||
let uuid = self.persist.uuids.get(&id)?;
|
||||
self.score.board.players_team(&uuid_text(*uuid))
|
||||
}
|
||||
pub(super) fn player_team(&self) -> Option<&sb::Team> {
|
||||
self.score.board.players_team(PLAYER_NAME)
|
||||
}
|
||||
/// The teams of the player and of the mobs on one (empty without teams).
|
||||
pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams {
|
||||
let board = &self.score.board;
|
||||
if board.teams.is_empty() {
|
||||
return Default::default();
|
||||
}
|
||||
horizon_client::mobs::Teams {
|
||||
player: self.player_team().cloned(),
|
||||
mobs: self
|
||||
.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.filter_map(|(id, uuid)| {
|
||||
Some((*id, board.players_team(&uuid_text(*uuid))?.clone()))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
/// The mobs on the player's team (`isAlliedTo`).
|
||||
pub(super) fn player_allies(&self) -> HashSet<u32> {
|
||||
let Some(team) = self.player_team() else {
|
||||
return HashSet::new();
|
||||
};
|
||||
self.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.filter(|(_, uuid)| team.players.contains(&uuid_text(**uuid)))
|
||||
.map(|(id, _)| *id)
|
||||
.collect()
|
||||
}
|
||||
/// `Player.getDisplayName`: the name with the team's prefix, suffix and colour.
|
||||
pub(super) fn player_display_comp(&self) -> Comp {
|
||||
let name = literal(PLAYER_NAME);
|
||||
match self.player_team() {
|
||||
Some(t) => t.formatted_name_comp(&name),
|
||||
None => name,
|
||||
}
|
||||
}
|
||||
pub(super) fn player_display_text(&self) -> Text {
|
||||
match self.player_team() {
|
||||
Some(t) => t.formatted_name(Text::literal(PLAYER_NAME)),
|
||||
None => Text::literal(PLAYER_NAME),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- commands ------------------------------------------------------------
|
||||
@@ -499,6 +579,62 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Hud.extractTabList`: the player list while the player-list key is
|
||||
/// held. A single-player world lists only its player, so it shows only
|
||||
/// with a `list` objective.
|
||||
pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) {
|
||||
use horizon_client::tab_list::{self, TabInputs, TabPlayer};
|
||||
let chatting = self.remote.is_some() && self.remote_chat_open();
|
||||
let key = self.screen == super::Screen::Playing
|
||||
&& !chatting
|
||||
&& self.keys.contains(&winit::keyboard::KeyCode::Tab);
|
||||
let (players, online_mode, upside_down) = match self.remote_tab_players() {
|
||||
Some(remote) => remote,
|
||||
None => {
|
||||
// The integrated server: the local player, online mode, no ping.
|
||||
let uuid = self.level.player_uuid.map_or(0, |u| {
|
||||
u.iter()
|
||||
.fold(0u128, |a, &w| (a << 32) | u128::from(w as u32))
|
||||
});
|
||||
let mut me = TabPlayer::new(uuid, PLAYER_NAME);
|
||||
me.game_mode = self.mode_id();
|
||||
me.skin = "entity/player/wide/steve".into();
|
||||
(vec![me], true, Vec::new())
|
||||
}
|
||||
};
|
||||
let board = &self.score.board;
|
||||
let objective = board.display_objective(sb::SLOT_LIST);
|
||||
let shown = tab_list::visible(
|
||||
key,
|
||||
self.remote.is_none(),
|
||||
players.len(),
|
||||
objective.is_some(),
|
||||
);
|
||||
self.tab_list.set_visible(shown);
|
||||
if !shown {
|
||||
return;
|
||||
}
|
||||
let up = |id: u128| upside_down.contains(&id);
|
||||
let inputs = TabInputs {
|
||||
players: &players,
|
||||
board,
|
||||
objective,
|
||||
screen_width: batch.width as i32,
|
||||
online_mode,
|
||||
gui_ticks: self.ticks as i64,
|
||||
// Horizon has no "chat background only" option: vanilla's default (on).
|
||||
background: tab_list::row_background(
|
||||
true,
|
||||
f64::from(self.settings.text_background_opacity),
|
||||
),
|
||||
upside_down: &up,
|
||||
};
|
||||
let draws = self.tab_list.layout(&inputs, &self.res.atlas.font);
|
||||
horizon_client::hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands' view of the game.
|
||||
struct GameEnv<'a, 'b> {
|
||||
g: &'a mut Game<'b>,
|
||||
|
||||
@@ -67,8 +67,9 @@ pub(super) struct SculkState {
|
||||
/// The player's warning level toward a warden.
|
||||
pub tracker: WardenSpawnTracker,
|
||||
tables: Tables,
|
||||
index: HashSet<(i32, i32, i32)>,
|
||||
known: HashSet<(i32, i32)>,
|
||||
/// The sculk block entities in the order they were added.
|
||||
index: Index,
|
||||
pub known: HashSet<(i32, i32)>,
|
||||
steps: HashMap<Who, Steps>,
|
||||
damaged: HashMap<u32, i64>,
|
||||
last_health: Option<f32>,
|
||||
@@ -77,7 +78,36 @@ pub(super) struct SculkState {
|
||||
/// Who causes the block changes being processed (the player's actions).
|
||||
pub actor: Option<Who>,
|
||||
ticks: u32,
|
||||
tracker_loaded: bool,
|
||||
pub tracker_loaded: bool,
|
||||
}
|
||||
/// An insertion-ordered set of block positions (`Level.blockEntityTickers`
|
||||
/// keeps the order block entities were added in).
|
||||
#[derive(Default)]
|
||||
struct Index {
|
||||
order: Vec<(i32, i32, i32)>,
|
||||
set: HashSet<(i32, i32, i32)>,
|
||||
}
|
||||
impl Index {
|
||||
fn insert(&mut self, key: (i32, i32, i32)) {
|
||||
if self.set.insert(key) {
|
||||
self.order.push(key);
|
||||
}
|
||||
}
|
||||
fn remove(&mut self, key: &(i32, i32, i32)) {
|
||||
if self.set.remove(key) {
|
||||
self.order.retain(|k| k != key);
|
||||
}
|
||||
}
|
||||
fn contains(&self, key: &(i32, i32, i32)) -> bool {
|
||||
self.set.contains(key)
|
||||
}
|
||||
fn iter(&self) -> impl Iterator<Item = &(i32, i32, i32)> {
|
||||
self.order.iter()
|
||||
}
|
||||
fn retain(&mut self, mut keep: impl FnMut(&(i32, i32, i32)) -> bool) {
|
||||
self.order.retain(|k| keep(k));
|
||||
self.set = self.order.iter().copied().collect();
|
||||
}
|
||||
}
|
||||
const KIND_SENSOR: u8 = 1;
|
||||
const KIND_CALIBRATED: u8 = 2;
|
||||
@@ -228,7 +258,7 @@ impl Game<'_> {
|
||||
|
||||
// ---- setup and the block entity index ----
|
||||
|
||||
fn sculk_prepare(&mut self) {
|
||||
pub(super) fn sculk_prepare(&mut self) {
|
||||
if self.sculk.tables.built {
|
||||
return;
|
||||
}
|
||||
@@ -293,7 +323,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Find the sculk blocks of chunks that just became resident, and apply
|
||||
/// the block writes recorded since the last tick.
|
||||
fn sculk_sync_index(&mut self) {
|
||||
pub(super) fn sculk_sync_index(&mut self) {
|
||||
// Chunks that arrived or left (every half second is plenty).
|
||||
if self.sculk.ticks.is_multiple_of(10) {
|
||||
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
|
||||
@@ -660,14 +690,22 @@ impl Game<'_> {
|
||||
|
||||
// ---- ticking ----
|
||||
|
||||
/// The block entities of sculk: vibration tickers and catalysts, then the
|
||||
/// entity-driven events of this tick.
|
||||
pub(super) fn tick_sculk(&mut self) -> Result<()> {
|
||||
/// The entity phase of a tick for sculk: the player's warden spawn
|
||||
/// tracker (`ServerPlayer.tick`), and the events of entities standing on
|
||||
/// and moving over blocks.
|
||||
pub(super) fn tick_sculk_entities(&mut self) {
|
||||
self.sculk.ticks = self.sculk.ticks.wrapping_add(1);
|
||||
self.sculk_prepare();
|
||||
self.load_warden_tracker();
|
||||
self.sculk.tracker.tick();
|
||||
self.tick_darkness_blend();
|
||||
self.sculk_step_on();
|
||||
self.tick_entity_events();
|
||||
}
|
||||
/// The block entity phase for sculk: vibration tickers and catalysts, in
|
||||
/// the order the block entities were added (`Level.tickBlockEntities`).
|
||||
pub(super) fn tick_sculk_blocks(&mut self) -> Result<()> {
|
||||
self.sculk_prepare();
|
||||
self.sculk_sync_index();
|
||||
let keys: Vec<(i32, i32, i32)> = self.sculk.index.iter().copied().collect();
|
||||
for key in keys {
|
||||
@@ -677,8 +715,6 @@ impl Game<'_> {
|
||||
}
|
||||
self.tick_sculk_block(key)?;
|
||||
}
|
||||
self.sculk_step_on();
|
||||
self.tick_entity_events();
|
||||
Ok(())
|
||||
}
|
||||
/// `ServerLevel.shouldTickBlocksAt`, as `tick_blocks` decides it.
|
||||
@@ -975,11 +1011,18 @@ impl Game<'_> {
|
||||
];
|
||||
self.audio.play(sound, Some(at), 5.0, 1.0);
|
||||
}
|
||||
/// `SpawnUtil.trySpawnMob` for a warden around the shrieker.
|
||||
/// `SpawnUtil.trySpawnMob(WARDEN, TRIGGERED, level, pos, 20, 5, 6,
|
||||
/// ON_TOP_OF_COLLIDER, false)`: every candidate spot creates a warden
|
||||
/// (`EntityType.create` draws its yaw from the level random and
|
||||
/// `finalizeSpawn` plays its agitated sound), which is discarded when
|
||||
/// `checkSpawnObstruction` fails.
|
||||
fn try_summon_warden(&mut self, key: (i32, i32, i32), warning: i32) -> bool {
|
||||
if warning < 4 {
|
||||
return false;
|
||||
}
|
||||
let Some(kind) = self.res.mob_types.get("minecraft:warden").cloned() else {
|
||||
return false;
|
||||
};
|
||||
for _ in 0..20 {
|
||||
let r = &mut self.world.random;
|
||||
let dx = r.next_int_bound(11).unwrap_or(0) - 5;
|
||||
@@ -992,17 +1035,27 @@ impl Game<'_> {
|
||||
f64::from(at.1),
|
||||
f64::from(at.2) + 0.5,
|
||||
];
|
||||
if !self.warden_fits(spot) {
|
||||
continue;
|
||||
}
|
||||
let Some(id) = self.spawn_mob("minecraft:warden", spot, false) else {
|
||||
continue;
|
||||
};
|
||||
let yaw = horizon_client::camera::wrap_degrees(self.world.random.next_float() * 360.0);
|
||||
self.next_entity += 1;
|
||||
let mut mob = Mob::new(
|
||||
self.next_entity,
|
||||
kind.clone(),
|
||||
horizon_core::geometry::Vec3::new(spot[0], spot[1], spot[2]),
|
||||
yaw,
|
||||
);
|
||||
// Warden.finalizeSpawn, then Mob.finalizeSpawn's draws from the
|
||||
// level random: the follow range bonus and left-handedness.
|
||||
let mut events = Vec::new();
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
warden::finalize(m, true, &mut events);
|
||||
}
|
||||
warden::finalize(&mut mob, true, &mut events);
|
||||
let _ = self.handle_mob_events(events);
|
||||
let r = &mut self.world.random;
|
||||
let bonus = r.triangle(0.0, 0.11485000000000001);
|
||||
mob.attrs.follow_range += mob.kind.follow_range * bonus;
|
||||
let _left_handed = r.next_float() < 0.05;
|
||||
if !self.warden_fits(&mob) {
|
||||
continue;
|
||||
}
|
||||
self.mobs.push(mob);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
@@ -1025,32 +1078,43 @@ impl Game<'_> {
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `Warden.checkSpawnObstruction`: no liquid and no collision in its box.
|
||||
fn warden_fits(&self, at: [f64; 3]) -> bool {
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
let Some(kind) = self.res.mob_types.get("minecraft:warden") else {
|
||||
/// `Warden.checkSpawnObstruction`: no liquid in its box, no living entity
|
||||
/// in the way (`isUnobstructed`), and no block collision.
|
||||
fn warden_fits(&self, mob: &Mob) -> bool {
|
||||
let bounds = mob.bounds();
|
||||
let player_blocks = !self.spectator()
|
||||
&& self.player.as_ref().is_some_and(|p| {
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
let b = horizon_core::geometry::Aabb::new(
|
||||
horizon_core::geometry::Vec3::new(
|
||||
p.position.x - w,
|
||||
p.position.y,
|
||||
p.position.z - w,
|
||||
),
|
||||
horizon_core::geometry::Vec3::new(
|
||||
p.position.x + w,
|
||||
p.position.y + f64::from(p.dimensions.height),
|
||||
p.position.z + w,
|
||||
),
|
||||
);
|
||||
!p.health.dead_or_dying() && b.intersects(bounds)
|
||||
});
|
||||
if player_blocks
|
||||
|| self
|
||||
.mobs
|
||||
.iter()
|
||||
.any(|m| !m.removed && m.alive() && m.bounds().intersects(bounds))
|
||||
{
|
||||
return false;
|
||||
};
|
||||
let half = kind.width / 2.0;
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(at[0] - half, at[1], at[2] - half),
|
||||
Vec3::new(at[0] + half, at[1] + kind.height, at[2] + half),
|
||||
);
|
||||
}
|
||||
let others: Vec<horizon_client::mobs::Seen> = Vec::new();
|
||||
let w = self.mob_world_base(&others);
|
||||
let min = [
|
||||
bounds.min_position().x,
|
||||
bounds.min_position().y,
|
||||
bounds.min_position().z,
|
||||
];
|
||||
let max = [
|
||||
bounds.max_position().x,
|
||||
bounds.max_position().y,
|
||||
bounds.max_position().z,
|
||||
];
|
||||
for x in min[0].floor() as i32..=max[0].floor() as i32 {
|
||||
for y in min[1].floor() as i32..=max[1].floor() as i32 {
|
||||
for z in min[2].floor() as i32..=max[2].floor() as i32 {
|
||||
let min = bounds.min_position();
|
||||
let max = bounds.max_position();
|
||||
// Level.containsAnyLiquid: floor(min) up to ceil(max), exclusive.
|
||||
for x in min.x.floor() as i32..max.x.ceil() as i32 {
|
||||
for y in min.y.floor() as i32..max.y.ceil() as i32 {
|
||||
for z in min.z.floor() as i32..max.z.ceil() as i32 {
|
||||
if w.fluid(x, y, z) != horizon_client::blocks::Fluid::None {
|
||||
return false;
|
||||
}
|
||||
@@ -1162,20 +1226,28 @@ impl Game<'_> {
|
||||
at: [f64; 3],
|
||||
experience: impl FnOnce(&mut Self) -> u32,
|
||||
) -> bool {
|
||||
// GameEventDispatcher: catalysts are BY_DISTANCE listeners, handled
|
||||
// nearest first (exact distance to the block centre); a tie keeps the
|
||||
// order they were visited in: chunk x, chunk z, section y, then the
|
||||
// order they registered in. The first one takes the experience.
|
||||
let source = block_of(at);
|
||||
let mut nearest: Option<((i32, i32, i32), i64)> = None;
|
||||
for key in self.sculk.index.iter().copied() {
|
||||
let d = dist_sqr(source, key);
|
||||
if d <= 64 && nearest.is_none_or(|(_, best)| d < best) {
|
||||
let is_catalyst = matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Sculk(e)) if e.kind == SculkKind::Catalyst
|
||||
);
|
||||
if is_catalyst {
|
||||
nearest = Some((key, d));
|
||||
}
|
||||
let mut candidates: Vec<(f64, (i32, i32, i32), usize, (i32, i32, i32))> = Vec::new();
|
||||
for (order, key) in self.sculk.index.iter().copied().enumerate() {
|
||||
if dist_sqr(source, key) > 64 {
|
||||
continue;
|
||||
}
|
||||
let is_catalyst = matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Sculk(e)) if e.kind == SculkKind::Catalyst
|
||||
);
|
||||
if is_catalyst {
|
||||
let c = center(key);
|
||||
let d = (at[0] - c[0]).powi(2) + (at[1] - c[1]).powi(2) + (at[2] - c[2]).powi(2);
|
||||
candidates.push((d, (key.0 >> 4, key.2 >> 4, key.1 >> 4), order, key));
|
||||
}
|
||||
}
|
||||
candidates.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));
|
||||
let nearest = candidates.first().map(|c| (c.3, ()));
|
||||
let Some((key, _)) = nearest else {
|
||||
return false;
|
||||
};
|
||||
@@ -1197,7 +1269,8 @@ impl Game<'_> {
|
||||
let c = center(key);
|
||||
let options = ParticleOptions::simple(ParticleType::SculkSoul);
|
||||
for _ in 0..2 {
|
||||
let r = &mut self.world.random;
|
||||
// Client-side (LevelEventHandler / particles): the client random.
|
||||
let r = self.particles.random();
|
||||
let p = [
|
||||
c[0] + r.next_gaussian() * 0.2,
|
||||
c[1] + 0.65,
|
||||
@@ -1217,7 +1290,8 @@ impl Game<'_> {
|
||||
let c = center((pos.x, pos.y, pos.z));
|
||||
let count = data >> 6;
|
||||
if count > 0 {
|
||||
let r = &mut self.world.random;
|
||||
// Client-side (LevelEventHandler / particles): the client random.
|
||||
let r = self.particles.random();
|
||||
if r.next_float() < 0.3 + count as f32 * 0.1 {
|
||||
let volume = 0.15 + 0.02 * (count * count) as f32 * r.next_float();
|
||||
let pitch = 0.4 + 0.3 * count as f32 * r.next_float();
|
||||
@@ -1256,7 +1330,11 @@ impl Game<'_> {
|
||||
.collect()
|
||||
};
|
||||
for (direction, roll, factor) in faces {
|
||||
let repetitions = self.world.random.next_int_bound(count + 1).unwrap_or(0);
|
||||
let repetitions = self
|
||||
.particles
|
||||
.random()
|
||||
.next_int_bound(count + 1)
|
||||
.unwrap_or(0);
|
||||
for _ in 0..repetitions {
|
||||
self.spawn_particle_on_face(pos, direction, roll, factor);
|
||||
}
|
||||
@@ -1272,7 +1350,8 @@ impl Game<'_> {
|
||||
let (particles, spread) = if solid { (40, 0.45f32) } else { (20, 0.25f32) };
|
||||
let options = ParticleOptions::simple(ParticleType::SculkChargePop);
|
||||
for _ in 0..particles {
|
||||
let r = &mut self.world.random;
|
||||
// Client-side (LevelEventHandler / particles): the client random.
|
||||
let r = self.particles.random();
|
||||
let v = [
|
||||
2.0 * r.next_float() - 1.0,
|
||||
2.0 * r.next_float() - 1.0,
|
||||
@@ -1296,7 +1375,8 @@ impl Game<'_> {
|
||||
fn spawn_particle_on_face(&mut self, pos: BlockPos, face: Direction, roll: f32, factor: f64) {
|
||||
let c = center((pos.x, pos.y, pos.z));
|
||||
let step = face.normal();
|
||||
let r = &mut self.world.random;
|
||||
// Client-side (LevelEventHandler / particles): the client random.
|
||||
let r = self.particles.random();
|
||||
let mut jitter = || r.next_double() - 0.5;
|
||||
let mut at = [0.0; 3];
|
||||
for i in 0..3 {
|
||||
@@ -1327,7 +1407,7 @@ impl Game<'_> {
|
||||
}
|
||||
let state = self.world.block(pos.x, pos.y, pos.z);
|
||||
if self.state_property(state, "waterlogged") != Some("true") {
|
||||
let pitch = 0.6 + self.world.random.next_float() * 0.4;
|
||||
let pitch = 0.6 + self.particles.random().next_float() * 0.4;
|
||||
self.audio.play(
|
||||
"minecraft:block.sculk_shrieker.shriek",
|
||||
Some([f64::from(pos.x) + 0.5, top, f64::from(pos.z) + 0.5]),
|
||||
@@ -1356,7 +1436,8 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
for _ in 0..30 {
|
||||
let r = &mut self.world.random;
|
||||
// Client-side (LevelEventHandler / particles): the client random.
|
||||
let r = self.particles.random();
|
||||
let off = |v: f32| f64::from(v * 1.4 - 0.7);
|
||||
let p = [
|
||||
at[0] + off(r.next_float()),
|
||||
|
||||
@@ -0,0 +1,674 @@
|
||||
//! The Rust side of tools/test_sculk_parity.py: with
|
||||
//! `HORIZON_SCULK_FIXTURE=SCENARIOS,OUTPUT` the game loads its resources and
|
||||
//! runs every scenario (sculk blocks, the player with a warning level, scripted
|
||||
//! game events and block changes) through its own sculk code on a fresh
|
||||
//! headless world, ticking in `ServerLevel.tick`'s order, and prints what
|
||||
//! changed after every tick in the format of `VanillaSculkOracle`.
|
||||
use super::{Game, dispense_fixture};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
chunk::{Chunk, MIN_Y},
|
||||
command::args::GameMode,
|
||||
containers::BlockEntity,
|
||||
mobs::{Mob, Who},
|
||||
motion::PlayerMotion,
|
||||
sculk::{Info, SculkKind, WardenSpawnTracker},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Direction, Vec3},
|
||||
position::BlockPos,
|
||||
random::LegacyRandom,
|
||||
};
|
||||
use horizon_world::{chunk::BlockState, level::Ticks, registry::BlockStateId};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
fmt::Write as _,
|
||||
io::Write as _,
|
||||
sync::Arc,
|
||||
};
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
struct MobSpec {
|
||||
kind: String,
|
||||
pos: [f64; 3],
|
||||
yaw: f32,
|
||||
seed: i64,
|
||||
flags: Vec<String>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Scenario {
|
||||
name: String,
|
||||
ticks: i32,
|
||||
origin: [i32; 2],
|
||||
level_seed: i64,
|
||||
difficulty: String,
|
||||
wardens: bool,
|
||||
blocks: Vec<Vec<String>>,
|
||||
player: Option<[f64; 3]>,
|
||||
mode: String,
|
||||
sneak: bool,
|
||||
warning: Option<i32>,
|
||||
mobs: Vec<MobSpec>,
|
||||
watch: Vec<[i32; 3]>,
|
||||
regions: Vec<[i32; 6]>,
|
||||
actions: Vec<(i32, Vec<String>)>,
|
||||
}
|
||||
|
||||
fn parse(text: &str) -> Vec<Scenario> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur: Option<Scenario> = None;
|
||||
for line in text.lines() {
|
||||
let f: Vec<&str> = line.split_whitespace().collect();
|
||||
if f.is_empty() || f[0].starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let s = cur.get_or_insert_with(Scenario::default);
|
||||
match f[0] {
|
||||
"scenario" => {
|
||||
s.name = f[1].to_owned();
|
||||
s.difficulty = "normal".into();
|
||||
s.wardens = true;
|
||||
s.mode = "survival".into();
|
||||
for kv in &f[2..] {
|
||||
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
|
||||
match k {
|
||||
"ticks" => s.ticks = v.parse().unwrap_or(0),
|
||||
"levelseed" => s.level_seed = v.parse().unwrap_or(0),
|
||||
"difficulty" => s.difficulty = v.to_owned(),
|
||||
"nowardens" => s.wardens = false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
"origin" => s.origin = [f[1].parse().unwrap_or(0), f[2].parse().unwrap_or(0)],
|
||||
"fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()),
|
||||
"player" => {
|
||||
s.player = Some([
|
||||
f[1].parse().unwrap_or(0.0),
|
||||
f[2].parse().unwrap_or(0.0),
|
||||
f[3].parse().unwrap_or(0.0),
|
||||
]);
|
||||
for w in &f[4..] {
|
||||
if *w == "sneak" {
|
||||
s.sneak = true;
|
||||
} else if let Some(level) = w.strip_prefix("warn=") {
|
||||
s.warning = level.parse().ok();
|
||||
} else {
|
||||
s.mode = (*w).to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
"mob" => s.mobs.push(MobSpec {
|
||||
kind: f[1].to_owned(),
|
||||
pos: [
|
||||
f[2].parse().unwrap_or(0.0),
|
||||
f[3].parse().unwrap_or(0.0),
|
||||
f[4].parse().unwrap_or(0.0),
|
||||
],
|
||||
yaw: f[5].parse().unwrap_or(0.0),
|
||||
seed: f[6].parse().unwrap_or(0),
|
||||
flags: f[7..].iter().map(|x| (*x).to_owned()).collect(),
|
||||
}),
|
||||
"watch" => s.watch.push([
|
||||
f[1].parse().unwrap_or(0),
|
||||
f[2].parse().unwrap_or(0),
|
||||
f[3].parse().unwrap_or(0),
|
||||
]),
|
||||
"region" => {
|
||||
let n = |i: usize| f[i].parse::<i32>().unwrap_or(0);
|
||||
s.regions.push([n(1), n(2), n(3), n(4), n(5), n(6)]);
|
||||
}
|
||||
"at" => s.actions.push((
|
||||
f[1].parse().unwrap_or(0),
|
||||
f[2..].iter().map(|x| (*x).to_owned()).collect(),
|
||||
)),
|
||||
"end" => out.extend(cur.take()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn d(v: f64) -> String {
|
||||
format!("{:x}", v.to_bits())
|
||||
}
|
||||
fn f(v: f32) -> String {
|
||||
format!("{:x}", v.to_bits())
|
||||
}
|
||||
|
||||
/// Sounds the client plays for level events (3006 sculk charge, 3007
|
||||
/// shriek): vanilla's server never sends them.
|
||||
const CLIENT_SOUNDS: &[&str] = &[
|
||||
"minecraft:block.sculk_shrieker.shriek",
|
||||
"minecraft:block.sculk.charge",
|
||||
];
|
||||
|
||||
impl Game<'_> {
|
||||
/// Run every scenario of `spec` ("SCENARIOS,OUTPUT") and write the results.
|
||||
pub(super) fn sculk_fixture(&mut self, spec: &str) -> Result<()> {
|
||||
let (input, output) = spec
|
||||
.split_once(',')
|
||||
.ok_or("HORIZON_SCULK_FIXTURE=SCENARIOS,OUTPUT")?;
|
||||
let text = std::fs::read_to_string(input)?;
|
||||
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
|
||||
for s in parse(&text) {
|
||||
writeln!(out, "== {}", s.name)?;
|
||||
match self.sculk_scenario(&s) {
|
||||
Ok(lines) => out.write_all(lines.as_bytes())?,
|
||||
Err(e) => writeln!(out, "0 failed {e}")?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `minecraft:name[key=value,...]` to a state.
|
||||
fn fixture_state(&self, text: &str) -> Result<BlockStateId> {
|
||||
let (name, props) = match text.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (text, ""),
|
||||
};
|
||||
let registry = self.res.assets.registry;
|
||||
let base = registry
|
||||
.default_state(name)
|
||||
.ok_or_else(|| format!("unknown block {name}"))?;
|
||||
let mut properties: BTreeMap<String, String> = registry
|
||||
.state(base)
|
||||
.map(|s| s.properties.clone().into_iter().collect())
|
||||
.unwrap_or_default();
|
||||
for kv in props.split(',').filter(|s| !s.is_empty()) {
|
||||
let (k, v) = kv.split_once('=').ok_or("property")?;
|
||||
properties.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
Ok(registry.resolve(&BlockState {
|
||||
name: name.to_owned(),
|
||||
properties,
|
||||
})?)
|
||||
}
|
||||
|
||||
/// `BlockStateParser.serialize`.
|
||||
fn fixture_state_text(&self, state: BlockStateId) -> String {
|
||||
let Some(s) = self.res.assets.registry.state(state) else {
|
||||
return "?".into();
|
||||
};
|
||||
if s.properties.is_empty() {
|
||||
return s.name.clone();
|
||||
}
|
||||
let mut sorted: Vec<(&String, &String)> = s.properties.iter().collect();
|
||||
sorted.sort();
|
||||
let props: Vec<String> = sorted.iter().map(|(k, v)| format!("{k}={v}")).collect();
|
||||
format!("{}[{}]", s.name, props.join(","))
|
||||
}
|
||||
|
||||
fn fixture_who(&self, who: Option<Who>, names: &HashMap<u32, String>) -> String {
|
||||
match who {
|
||||
None => "none".into(),
|
||||
Some(Who::Player) => "player".into(),
|
||||
Some(Who::Mob(id)) => names.get(&id).cloned().unwrap_or_else(|| format!("e{id}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_info(&self, info: Option<&Info>, names: &HashMap<u32, String>) -> String {
|
||||
let Some(i) = info else {
|
||||
return "-".into();
|
||||
};
|
||||
// A source entity that is gone reads as none (VibrationInfo.getEntity).
|
||||
let alive = |w: Option<Who>| match w {
|
||||
Some(Who::Mob(id)) if !self.mobs.iter().any(|m| m.id == id && !m.removed) => None,
|
||||
other => other,
|
||||
};
|
||||
format!(
|
||||
"{}/{}/{},{},{}/{}/{}",
|
||||
i.event.trim_start_matches("minecraft:"),
|
||||
f(i.distance),
|
||||
d(i.pos[0]),
|
||||
d(i.pos[1]),
|
||||
d(i.pos[2]),
|
||||
self.fixture_who(alive(i.source), names),
|
||||
self.fixture_who(alive(i.owner), names)
|
||||
)
|
||||
}
|
||||
|
||||
fn sculk_describe(&self, p: [i32; 3], names: &HashMap<u32, String>) -> String {
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
let mut line = self.fixture_state_text(state);
|
||||
if let Some(BlockEntity::Sculk(e)) = self.world.block_entities.get(&(p[0], p[1], p[2])) {
|
||||
let vibration = |line: &mut String| {
|
||||
let v = &e.vibration;
|
||||
let _ = write!(
|
||||
line,
|
||||
" cur={} travel={}",
|
||||
self.fixture_info(v.current.as_ref(), names),
|
||||
v.travel
|
||||
);
|
||||
match v.selector.current() {
|
||||
None => line.push_str(" sel=-"),
|
||||
Some((info, tick)) => {
|
||||
let _ = write!(
|
||||
line,
|
||||
" sel={}@{tick}",
|
||||
self.fixture_info(Some(&info), names)
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
match e.kind {
|
||||
SculkKind::Sensor | SculkKind::Calibrated => {
|
||||
let _ = write!(line, " freq={}", e.last_frequency);
|
||||
vibration(&mut line);
|
||||
}
|
||||
SculkKind::Shrieker => {
|
||||
let _ = write!(line, " warn={}", e.warning_level);
|
||||
vibration(&mut line);
|
||||
}
|
||||
SculkKind::Catalyst => {
|
||||
let _ = write!(line, " cursors={}", e.spreader.cursors.len());
|
||||
for c in &e.spreader.cursors {
|
||||
let _ = write!(
|
||||
line,
|
||||
" {},{},{}:{}:{}:{}:",
|
||||
c.pos.x, c.pos.y, c.pos.z, c.charge, c.update_delay, c.decay_delay
|
||||
);
|
||||
match &c.facings {
|
||||
None => line.push('-'),
|
||||
Some(faces) => {
|
||||
let mut faces = faces.clone();
|
||||
faces.sort_by_key(|d| *d as u8);
|
||||
for d in faces {
|
||||
line.push(match d {
|
||||
Direction::Down => 'd',
|
||||
Direction::Up => 'u',
|
||||
Direction::North => 'n',
|
||||
Direction::South => 's',
|
||||
Direction::West => 'w',
|
||||
Direction::East => 'e',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
fn sculk_fixture_reset(&mut self, s: &Scenario) -> Result<()> {
|
||||
self.world = World::new(self.res.facts.air, 0);
|
||||
let plains = u32::from(self.res.biomes.id("minecraft:plains"));
|
||||
let layers = [
|
||||
self.fixture_state("minecraft:bedrock")?,
|
||||
self.fixture_state("minecraft:dirt")?,
|
||||
self.fixture_state("minecraft:dirt")?,
|
||||
self.fixture_state("minecraft:grass_block")?,
|
||||
];
|
||||
let (ocx, ocz) = (s.origin[0] >> 4, s.origin[1] >> 4);
|
||||
for cx in ocx - 4..=ocx + 4 {
|
||||
for cz in ocz - 4..=ocz + 4 {
|
||||
let mut chunk = Chunk::empty(cx, cz);
|
||||
for section in &mut chunk.sections {
|
||||
Arc::make_mut(section).biomes = horizon_core::paletted::PalettedContainer::new(
|
||||
horizon_client::chunk::BIOME_STRATEGY,
|
||||
plains,
|
||||
);
|
||||
}
|
||||
chunk.lit = true;
|
||||
self.world.chunks.insert((cx, cz), Arc::new(chunk));
|
||||
for x in 0..16 {
|
||||
for z in 0..16 {
|
||||
for (y, layer) in layers.iter().enumerate() {
|
||||
self.world
|
||||
.set(cx * 16 + x, MIN_Y + y as i32, cz * 16 + z, *layer)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.block_ticks = Ticks::new(0);
|
||||
self.tick_chunks.clear();
|
||||
self.sync_tick_chunks();
|
||||
self.mobs.clear();
|
||||
self.dropped.clear();
|
||||
self.orbs.clear();
|
||||
self.level_events.clear();
|
||||
self.ui.rules = Default::default();
|
||||
for (rule, value) in [
|
||||
("spawn_mobs", false),
|
||||
("spawn_monsters", false),
|
||||
("spawn_patrols", false),
|
||||
("spawn_phantoms", false),
|
||||
("spawn_wandering_traders", false),
|
||||
("advance_time", false),
|
||||
("advance_weather", false),
|
||||
("raids", false),
|
||||
("spawn_wardens", s.wardens),
|
||||
] {
|
||||
self.ui
|
||||
.rules
|
||||
.set(rule, horizon_client::gamerules::Value::Bool(value));
|
||||
}
|
||||
self.ui.rules.set(
|
||||
"random_tick_speed",
|
||||
horizon_client::gamerules::Value::Int(0),
|
||||
);
|
||||
use horizon_world::food::Difficulty;
|
||||
let difficulty = match s.difficulty.as_str() {
|
||||
"peaceful" => Difficulty::Peaceful,
|
||||
"easy" => Difficulty::Easy,
|
||||
"hard" => Difficulty::Hard,
|
||||
_ => Difficulty::Normal,
|
||||
};
|
||||
self.world.health_rules.difficulty = difficulty;
|
||||
self.ui.difficulty = match difficulty {
|
||||
Difficulty::Peaceful => 0,
|
||||
Difficulty::Easy => 1,
|
||||
Difficulty::Normal => 2,
|
||||
Difficulty::Hard => 3,
|
||||
};
|
||||
self.level.seed = 0;
|
||||
self.potions.effects = Default::default();
|
||||
self.sculk = Default::default();
|
||||
self.sculk.tracker_loaded = true;
|
||||
self.sculk_prepare();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sculk_scenario(&mut self, s: &Scenario) -> Result<String> {
|
||||
self.sculk_fixture_reset(s)?;
|
||||
let at = s.player.unwrap_or([
|
||||
f64::from(s.origin[0]) + 0.5,
|
||||
100.0,
|
||||
f64::from(s.origin[1]) + 0.5,
|
||||
]);
|
||||
self.mode = match s.mode.as_str() {
|
||||
"creative" => GameMode::Creative,
|
||||
"spectator" => GameMode::Spectator,
|
||||
"adventure" => GameMode::Adventure,
|
||||
_ => GameMode::Survival,
|
||||
};
|
||||
self.creative = self.mode == GameMode::Creative;
|
||||
let mut player = PlayerMotion::new(self.motion, Vec3::new(at[0], at[1], at[2]))?;
|
||||
player.spectator = self.mode == GameMode::Spectator;
|
||||
self.player = Some(player);
|
||||
self.keys.clear();
|
||||
if s.sneak {
|
||||
self.keys.insert(KeyCode::ShiftLeft);
|
||||
}
|
||||
self.sculk.tracker = WardenSpawnTracker::default();
|
||||
if let Some(level) = s.warning {
|
||||
self.sculk.tracker.set_warning_level(level);
|
||||
}
|
||||
// The blocks, in order (sculk block entities tick in the order they
|
||||
// were placed), with `Level.setBlock(pos, state, 2 | 16)` at game time 1000.
|
||||
self.world.game_time = 1000;
|
||||
let mut cells = Vec::new();
|
||||
for b in &s.blocks {
|
||||
let n = |i: usize| b[i].parse::<i32>().unwrap_or(0);
|
||||
if b[0] == "block" {
|
||||
cells.push((BlockPos::new(n(1), n(2), n(3)), self.fixture_state(&b[4])?));
|
||||
} else {
|
||||
let state = self.fixture_state(&b[7])?;
|
||||
for x in n(1).min(n(4))..=n(1).max(n(4)) {
|
||||
for y in n(2).min(n(5))..=n(2).max(n(5)) {
|
||||
for z in n(3).min(n(6))..=n(3).max(n(6)) {
|
||||
cells.push((BlockPos::new(x, y, z), state));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.with_level(|b, level, ticks| {
|
||||
for (pos, state) in cells {
|
||||
b.set_block(level, ticks, pos, state, 2 | 16);
|
||||
}
|
||||
});
|
||||
self.level_events.clear();
|
||||
self.sculk.known = self.world.chunks.keys().copied().collect();
|
||||
self.sculk_sync_index();
|
||||
let mut names: HashMap<u32, String> = HashMap::new();
|
||||
let mut sources: Vec<u32> = Vec::new();
|
||||
for spec in &s.mobs {
|
||||
let kind = self
|
||||
.res
|
||||
.mob_types
|
||||
.get(&spec.kind)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("unknown mob {}", spec.kind))?;
|
||||
let id = 100_000 + sources.len() as u32;
|
||||
let mut m = Mob::new(
|
||||
id,
|
||||
kind,
|
||||
Vec3::new(spec.pos[0], spec.pos[1], spec.pos[2]),
|
||||
spec.yaw,
|
||||
);
|
||||
for flag in &spec.flags {
|
||||
match flag.as_str() {
|
||||
"persistent" => m.persistent = true,
|
||||
"noai" => m.no_ai = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
m.random = LegacyRandom::new(spec.seed);
|
||||
// EntityType.create equips nothing (that is finalizeSpawn's job).
|
||||
for slot in [
|
||||
&mut m.extra.main_hand,
|
||||
&mut m.extra.off_hand,
|
||||
&mut m.extra.head,
|
||||
&mut m.extra.chest,
|
||||
&mut m.extra.legs,
|
||||
&mut m.extra.feet,
|
||||
] {
|
||||
*slot = None;
|
||||
}
|
||||
names.insert(id, format!("m{}", sources.len()));
|
||||
sources.push(id);
|
||||
self.mobs.push(m);
|
||||
}
|
||||
self.next_entity = self.next_entity.max(200_000);
|
||||
self.world.day_time = 6000;
|
||||
self.world.random = LegacyRandom::new(s.level_seed);
|
||||
self.audio.capture = Some(Vec::new());
|
||||
let mut known: HashSet<u32> = self.mobs.iter().map(|m| m.id).collect();
|
||||
let mut known_items = self.dropped.len();
|
||||
let mut known_orbs = self.orbs.len();
|
||||
let mut last: HashMap<[i32; 3], String> = HashMap::new();
|
||||
let mut region_last: HashMap<[i32; 3], String> = HashMap::new();
|
||||
let (mut last_player, mut last_rng) = (String::new(), String::new());
|
||||
let mut out = String::new();
|
||||
for t in 0..=s.ticks {
|
||||
dispense_fixture::start_recording();
|
||||
if t > 0 {
|
||||
self.sculk_fixture_tick(t, s, &sources)?;
|
||||
}
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for p in &s.watch {
|
||||
let line = self.sculk_describe(*p, &names);
|
||||
if last.get(p) != Some(&line) {
|
||||
last.insert(*p, line.clone());
|
||||
lines.push(format!("blk {},{},{} {line}", p[0], p[1], p[2]));
|
||||
}
|
||||
}
|
||||
// Regions: every block whose state changed.
|
||||
for r in &s.regions {
|
||||
for x in r[0]..=r[3] {
|
||||
for y in r[1]..=r[4] {
|
||||
for z in r[2]..=r[5] {
|
||||
let state = self.fixture_state_text(self.world.block(x, y, z));
|
||||
let before = region_last.insert([x, y, z], state.clone());
|
||||
if t > 0 && before.as_ref() != Some(&state) {
|
||||
lines.push(format!("set {x},{y},{z} {state}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let tr = self.sculk.tracker;
|
||||
let dark = self
|
||||
.potions
|
||||
.effects
|
||||
.get("darkness")
|
||||
.map_or("-".to_owned(), |e| e.duration.to_string());
|
||||
let now = format!(
|
||||
"warn {} {} dark {dark}",
|
||||
tr.warning_level, tr.cooldown_ticks
|
||||
);
|
||||
if now != last_player {
|
||||
last_player = now.clone();
|
||||
lines.push(now);
|
||||
}
|
||||
let mut fresh: Vec<&Mob> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| !known.contains(&m.id))
|
||||
.collect();
|
||||
fresh.sort_by_key(|m| m.id);
|
||||
let fresh: Vec<(u32, String)> = fresh
|
||||
.iter()
|
||||
.map(|m| {
|
||||
(
|
||||
m.id,
|
||||
format!(
|
||||
"new {} {},{},{}",
|
||||
m.kind.id,
|
||||
d(m.position.x),
|
||||
d(m.position.y),
|
||||
d(m.position.z)
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
for (id, line) in fresh {
|
||||
known.insert(id);
|
||||
names.insert(id, format!("n{}", names.len()));
|
||||
// An entity's own random is unseeded in vanilla: the oracle
|
||||
// seeds what appeared, and so does this.
|
||||
let seed = 0x5eed + names.len() as i64;
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.random = LegacyRandom::new(seed);
|
||||
horizon_client::mobs::warden::delay_sensors(m);
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
for i in known_items..self.dropped.len() {
|
||||
let d = &self.dropped[i];
|
||||
names.insert(u32::MAX - i as u32, format!("n{}", names.len()));
|
||||
lines.push(format!(
|
||||
"new minecraft:item {},{},{}",
|
||||
self::d(d.position.x),
|
||||
self::d(d.position.y),
|
||||
self::d(d.position.z)
|
||||
));
|
||||
}
|
||||
known_items = self.dropped.len();
|
||||
// Where an orb flies comes from its own random: its value only.
|
||||
for orb in &self.orbs[known_orbs.min(self.orbs.len())..] {
|
||||
lines.push(format!("new minecraft:experience_orb value={}", orb.value));
|
||||
}
|
||||
known_orbs = self.orbs.len();
|
||||
for line in dispense_fixture::stop_recording() {
|
||||
if let Some(rest) = line.strip_prefix("L ") {
|
||||
lines.push(format!("level {rest}"));
|
||||
}
|
||||
}
|
||||
for (sound, at, volume, pitch) in
|
||||
self.audio.capture.replace(Vec::new()).unwrap_or_default()
|
||||
{
|
||||
if CLIENT_SOUNDS.contains(&sound.as_str()) {
|
||||
continue;
|
||||
}
|
||||
lines.push(format!(
|
||||
"sound {sound} {},{},{} {} {}",
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
at[2].floor() as i32,
|
||||
f(volume),
|
||||
f(pitch)
|
||||
));
|
||||
}
|
||||
let rng = format!("rng {:x}", self.world.random.state());
|
||||
if rng != last_rng {
|
||||
last_rng = rng.clone();
|
||||
lines.push(rng);
|
||||
}
|
||||
for line in lines {
|
||||
let _ = writeln!(out, "{t} {line}");
|
||||
}
|
||||
}
|
||||
self.audio.capture = None;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One `ServerLevel.tick` of a scenario.
|
||||
fn sculk_fixture_tick(&mut self, t: i32, s: &Scenario, sources: &[u32]) -> Result<()> {
|
||||
self.world.game_time += 1;
|
||||
// Scheduled block and fluid ticks, then block events.
|
||||
self.tick_scheduled()?;
|
||||
self.with_level(|b, level, ticks| b.run_block_events(level, ticks));
|
||||
self.process_level_events()?;
|
||||
// The scenario's actions happen among the entities.
|
||||
for (tick, words) in &s.actions {
|
||||
if *tick != t {
|
||||
continue;
|
||||
}
|
||||
match words[0].as_str() {
|
||||
"event" => {
|
||||
let event = horizon_client::sculk::intern(&words[1])
|
||||
.ok_or_else(|| format!("unknown game event {}", words[1]))?;
|
||||
let num = |i: usize| words[i].parse::<f64>().unwrap_or(0.0);
|
||||
let pos = [num(2), num(3), num(4)];
|
||||
let who = match words[5].as_str() {
|
||||
"none" => None,
|
||||
"player" => Some(Who::Player),
|
||||
m => sources
|
||||
.get(m[1..].parse::<usize>().unwrap_or(usize::MAX))
|
||||
.map(|id| Who::Mob(*id)),
|
||||
};
|
||||
let state = match words.get(6) {
|
||||
Some(text) => Some(self.fixture_state(text)?),
|
||||
None => None,
|
||||
};
|
||||
let ctx = self.who_context(who, state);
|
||||
self.post_game_event(event, pos, ctx);
|
||||
}
|
||||
"kill" => {
|
||||
// LivingEntity.hurtServer with a player attack.
|
||||
let id = sources
|
||||
.get(words[1][1..].parse::<usize>().unwrap_or(usize::MAX))
|
||||
.copied()
|
||||
.ok_or("kill: no such mob")?;
|
||||
let amount = words
|
||||
.get(2)
|
||||
.and_then(|a| a.parse::<f32>().ok())
|
||||
.unwrap_or(1000.0);
|
||||
let at = self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z])
|
||||
.unwrap_or_default();
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.damage(amount, horizon_client::mobs::Damage::player(at));
|
||||
}
|
||||
self.last_hurt_by_player.insert(id);
|
||||
}
|
||||
"set" => {
|
||||
let n = |i: usize| words[i].parse::<i32>().unwrap_or(0);
|
||||
let pos = BlockPos::new(n(1), n(2), n(3));
|
||||
let state = self.fixture_state(&words[4])?;
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.set_block(level, ticks, pos, state, 3);
|
||||
});
|
||||
self.process_level_events()?;
|
||||
}
|
||||
other => return Err(format!("unknown action {other}").into()),
|
||||
}
|
||||
}
|
||||
// Entities: the player's warden spawn tracker, then the mobs.
|
||||
self.tick_sculk_entities();
|
||||
// (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.)
|
||||
self.tick_creature_entities()?;
|
||||
self.tick_items();
|
||||
// Block entities.
|
||||
self.tick_sculk_blocks()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,19 @@ use horizon_client::{
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
impl Game<'_> {
|
||||
/// An egg item at the parent, a plop and some experience.
|
||||
/// The egg item at the parent (`Sniffer.spawnChildFromBreeding`; the
|
||||
/// brain already played the plop and dropped the experience).
|
||||
pub(super) fn lay_sniffer_egg(&mut self, parent: &Mob) {
|
||||
let at = [parent.position.x, parent.position.y, parent.position.z];
|
||||
// new ItemEntity(level, x, y, z, stack): a little random push.
|
||||
let vx = self.world.random.next_double() * 0.2 - 0.1;
|
||||
let vz = self.world.random.next_double() * 0.2 - 0.1;
|
||||
self.spawn_item(
|
||||
ItemStack::new("minecraft:sniffer_egg", 1),
|
||||
at,
|
||||
[0.0, 0.2, 0.0],
|
||||
[vx, 0.2, vz],
|
||||
10,
|
||||
);
|
||||
let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 0.5;
|
||||
self.audio
|
||||
.play("minecraft:block.sniffer_egg.plop", Some(at), 1.0, pitch);
|
||||
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
|
||||
self.spawn_orbs(at, xp);
|
||||
}
|
||||
/// A snifflet where the egg was.
|
||||
pub(super) fn hatch_sniffer(&mut self, pos: [i32; 3]) {
|
||||
@@ -42,8 +41,10 @@ impl Game<'_> {
|
||||
m.head_yaw = yaw;
|
||||
}
|
||||
}
|
||||
/// `Sniffer.emitDiggingParticles`: block dust and the digging sound
|
||||
/// between the 1.7th and the 6th second of the digging animation.
|
||||
/// The sniffer's client-side effects: `SnifferSoundInstance` when it
|
||||
/// starts digging, `Sniffer.emitDiggingParticles` (block dust and the
|
||||
/// block's hit sound between the 1.7th and the 6th second of the
|
||||
/// digging animation) and `playSearchingSound`.
|
||||
pub(super) fn tick_sniffer_effects(&mut self) {
|
||||
let Some(camera) = self.player.as_ref().map(|p| p.position) else {
|
||||
return;
|
||||
@@ -52,14 +53,27 @@ impl Game<'_> {
|
||||
let m = &self.mobs[i];
|
||||
if m.species() != Species::Sniffer
|
||||
|| !m.alive()
|
||||
|| !sniffer::digging(m)
|
||||
|| m.silent
|
||||
|| m.position.distance_squared(camera) > 32.0 * 32.0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
if sniffer::state(m) == sniffer::SEARCHING && m.age.is_multiple_of(20) {
|
||||
self.audio
|
||||
.play("minecraft:entity.sniffer.searching", Some(at), 1.0, 1.0);
|
||||
continue;
|
||||
}
|
||||
if !sniffer::digging(m) {
|
||||
continue;
|
||||
}
|
||||
let Some(ms) = m.anim.states[3].millis(m.age as f32) else {
|
||||
continue;
|
||||
};
|
||||
if ms == 0 {
|
||||
self.audio
|
||||
.play("minecraft:entity.sniffer.digging", Some(at), 1.0, 1.0);
|
||||
}
|
||||
if ms <= 1700 || ms >= 6000 {
|
||||
continue;
|
||||
}
|
||||
@@ -68,19 +82,19 @@ impl Game<'_> {
|
||||
let Some((sprite, tint)) = self.particle_sprite(below) else {
|
||||
continue;
|
||||
};
|
||||
let at = [
|
||||
let dust = [
|
||||
f64::from(head[0]) + 0.5,
|
||||
f64::from(head[1]) + 0.5 - f64::from(0.65_f32),
|
||||
f64::from(head[2]) + 0.5,
|
||||
];
|
||||
for _ in 0..30 {
|
||||
let particle =
|
||||
Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint);
|
||||
Particle::terrain(&mut self.world.random, dust, [0.0; 3], sprite.clone(), tint);
|
||||
self.particles.push(particle);
|
||||
}
|
||||
if self.mobs[i].age.is_multiple_of(10) {
|
||||
self.audio
|
||||
.play("minecraft:entity.sniffer.digging", Some(at), 0.5, 0.5);
|
||||
let hit = self.res.facts.get(below).sounds.hit.clone();
|
||||
self.audio.play(&hit, Some(at), 0.5, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
//! Block entities removed by the block behaviour (`LevelChunk.setBlockState`
|
||||
//! running `BlockEntity.preRemoveSideEffects`) and the resources a destroyed
|
||||
//! block drops (`Block.dropResources`), drawn from the level random at the
|
||||
//! moment vanilla draws them. The item entities they make are added to the
|
||||
//! world as soon as the behaviour returns, within the same tick.
|
||||
use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box};
|
||||
use horizon_client::{
|
||||
containers::{Banner, BlockEntity},
|
||||
items::ItemStack,
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::{
|
||||
level::{
|
||||
LevelEvent,
|
||||
removal::{self, PreRemove},
|
||||
},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// What a broken block's entity gives its own dropped item (`copy_components`
|
||||
/// in the block loot tables): a shulker box's contents, a banner's layers, a
|
||||
/// container's custom name.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Pending {
|
||||
pub(super) shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
|
||||
pub(super) banner: HashMap<[i32; 3], Banner>,
|
||||
/// The block's item and the custom name.
|
||||
pub(super) names: HashMap<[i32; 3], (String, String)>,
|
||||
/// A decorated pot's sherds (back, left, right, front).
|
||||
pub(super) pot: HashMap<[i32; 3], [Option<ItemStack>; 4]>,
|
||||
}
|
||||
impl Pending {
|
||||
/// Remember what the block entity at `pos` copies into the drops of `block`.
|
||||
pub(super) fn record(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
entity: &BlockEntity,
|
||||
block: &str,
|
||||
name: Option<String>,
|
||||
) {
|
||||
if let BlockEntity::Banner(banner) = entity {
|
||||
self.banner.insert(pos, banner.clone());
|
||||
return;
|
||||
}
|
||||
if let Some(name) = name {
|
||||
self.names.insert(pos, (block.to_owned(), name));
|
||||
}
|
||||
if is_shulker_box(block)
|
||||
&& let BlockEntity::Chest(items) = entity
|
||||
{
|
||||
let kept = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| Some((i as u8, s.clone()?)))
|
||||
.collect();
|
||||
self.shulker.insert(pos, kept);
|
||||
}
|
||||
}
|
||||
/// Copy what was remembered for `pos` into a drop of the block.
|
||||
pub(super) fn attach(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if is_shulker_box(&stack.item)
|
||||
&& let Some(contents) = self.shulker.remove(&pos)
|
||||
&& !contents.is_empty()
|
||||
{
|
||||
stack.data_mut().container = contents;
|
||||
}
|
||||
if self
|
||||
.names
|
||||
.get(&pos)
|
||||
.is_some_and(|(item, _)| **item == *stack.item)
|
||||
&& let Some((_, name)) = self.names.remove(&pos)
|
||||
{
|
||||
stack.data_mut().custom_name = Some(name);
|
||||
}
|
||||
if &*stack.item == "minecraft:decorated_pot" {
|
||||
// The pot's block entity always copies its decorations, empty or not.
|
||||
let sides = self.pot.remove(&pos).unwrap_or_default();
|
||||
stack.data_mut().pot_decorations = Some(Box::new(sides));
|
||||
}
|
||||
if stack.item.ends_with("_banner")
|
||||
&& let Some(Banner { layers, name }) = self.banner.remove(&pos)
|
||||
{
|
||||
let data = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
if name.is_some() {
|
||||
data.custom_name = name;
|
||||
}
|
||||
stack.tidy();
|
||||
}
|
||||
}
|
||||
/// Remember a decorated pot's sherds from its saved block entity.
|
||||
pub(super) fn record_saved(&mut self, pos: [i32; 3], tag: &horizon_world::nbt::Tag) {
|
||||
use horizon_world::nbt::Tag;
|
||||
if tag.get("id") != Some(&Tag::String("minecraft:decorated_pot".into())) {
|
||||
return;
|
||||
}
|
||||
let sherds = tag.get("sherds");
|
||||
let side = |name: &str| match sherds.and_then(|s| s.get(name)) {
|
||||
Some(Tag::String(id)) => Some(ItemStack {
|
||||
item: std::sync::Arc::from(id.to_string_lossy().as_str()),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
}),
|
||||
Some(t) => horizon_client::save::item_from_nbt(t),
|
||||
None => None,
|
||||
};
|
||||
self.pot.insert(
|
||||
pos,
|
||||
[side("back"), side("left"), side("right"), side("front")],
|
||||
);
|
||||
}
|
||||
/// The block entity's dynamic drops: a decorated pot's sherds, left,
|
||||
/// back, front then right (`DecoratedPotBlock.getDrops`).
|
||||
pub(super) fn dynamic(&self, pos: [i32; 3]) -> Vec<ItemStack> {
|
||||
self.pot
|
||||
.get(&pos)
|
||||
.map_or_else(Vec::new, |[back, left, right, front]| {
|
||||
[left, back, front, right]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
pub(super) fn clear(&mut self, pos: [i32; 3]) {
|
||||
self.pot.remove(&pos);
|
||||
self.shulker.remove(&pos);
|
||||
self.banner.remove(&pos);
|
||||
self.names.remove(&pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// An item entity to add: where, its motion (None: `new ItemEntity`'s own
|
||||
/// random motion) and its pickup delay.
|
||||
pub(super) struct Spawn {
|
||||
pub(super) stack: ItemStack,
|
||||
pub(super) pos: [f64; 3],
|
||||
pub(super) motion: Option<[f64; 3]>,
|
||||
pub(super) delay: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Spill {
|
||||
pub(super) spawns: Vec<Spawn>,
|
||||
/// Experience orbs (`ExperienceOrb.award`): where and how much, each
|
||||
/// having drawn its merge id from the level random.
|
||||
pub(super) orbs: Vec<([f64; 3], u32)>,
|
||||
/// Block entities the behaviour removed, for the game's own follow-ups
|
||||
/// (open screens, playing songs).
|
||||
pub(super) removed: Vec<([i32; 3], BlockEntity)>,
|
||||
}
|
||||
|
||||
/// `Block.popResource`: a spot around the block's centre from the level random.
|
||||
pub(super) fn pop_position(
|
||||
random: &mut impl horizon_core::random::RandomSource,
|
||||
pos: [i32; 3],
|
||||
) -> [f64; 3] {
|
||||
let mut offset = || -0.25 + random.next_double() * 0.5;
|
||||
// EntityTypes.ITEM is 0.25 high.
|
||||
let half_height = f64::from(0.25f32) / 2.0;
|
||||
[
|
||||
f64::from(pos[0]) + 0.5 + offset(),
|
||||
f64::from(pos[1]) + 0.5 + offset() - half_height,
|
||||
f64::from(pos[2]) + 0.5 + offset(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The block entity at `pos` Horizon keeps as it was loaded, if any
|
||||
/// (campfires, decorated pots, chiseled bookshelves, shelves).
|
||||
pub(super) fn saved_entity(
|
||||
world: &horizon_client::world::World,
|
||||
pos: [i32; 3],
|
||||
) -> Option<horizon_world::nbt::Tag> {
|
||||
use horizon_world::nbt::Tag;
|
||||
let saved = world
|
||||
.chunks
|
||||
.get(&(pos[0] >> 4, pos[2] >> 4))?
|
||||
.saved
|
||||
.as_ref()?;
|
||||
saved
|
||||
.block_entities
|
||||
.iter()
|
||||
.find(|t| {
|
||||
t.get("x") == Some(&Tag::Int(pos[0]))
|
||||
&& t.get("y") == Some(&Tag::Int(pos[1]))
|
||||
&& t.get("z") == Some(&Tag::Int(pos[2]))
|
||||
})
|
||||
.cloned()
|
||||
}
|
||||
|
||||
impl GameLevel<'_> {
|
||||
/// `Block.popResource(level, pos, stack)` with the broken block's copied components.
|
||||
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
|
||||
self.pending.attach(pos, &mut stack);
|
||||
let at = pop_position(&mut self.world.random, pos);
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack,
|
||||
pos: at,
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
}
|
||||
/// `Block.popResource(level, pos, new ItemStack(block))`.
|
||||
pub(super) fn pop_block_item(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
let item = self.facts.get(state).item.clone();
|
||||
if &*item != "minecraft:air" {
|
||||
self.pop_resource([pos.x, pos.y, pos.z], ItemStack::new(&item, 1));
|
||||
}
|
||||
}
|
||||
/// An item `atLowerCornerWithOffset(pos, 0.5, 1.01, 0.5).offsetRandomXZ(random,
|
||||
/// 0.7)` with the default pickup delay (`ComposterBlock.extractProduce`).
|
||||
pub(super) fn pop_above(&mut self, pos: BlockPos, item: std::sync::Arc<str>) {
|
||||
let at = removal::jukebox_pop_position(&mut self.world.random, pos);
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: ItemStack::new(&item, 1),
|
||||
pos: at,
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
}
|
||||
/// `Block.dropResources(state, level, pos, blockEntity)`: the block's loot
|
||||
/// (from its random sequence, else the level random), with what its block
|
||||
/// entity copies into it, popped at once.
|
||||
pub(super) fn drop_resources_now(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
let at = [pos.x, pos.y, pos.z];
|
||||
if let Some(entity) = self.world.block_entities.get(&key) {
|
||||
let entity = entity.clone();
|
||||
let name = self.world.block_names.get(&key).cloned();
|
||||
let block = self.facts.get(state).name.clone();
|
||||
self.pending.record(at, &entity, &block, name);
|
||||
} else if let Some(tag) = saved_entity(self.world, [pos.x, pos.y, pos.z]) {
|
||||
self.pending.record_saved(at, &tag);
|
||||
}
|
||||
let dynamic = self.pending.dynamic(at);
|
||||
let drops = match self.items.block_loot_sequence(self.registry, state) {
|
||||
Some(sequence) => {
|
||||
let random = self.rand_sequences.get(&sequence, self.seed);
|
||||
self.items
|
||||
.block_drops_with(self.registry, state, None, &dynamic, random)
|
||||
}
|
||||
None => self.items.block_drops_with(
|
||||
self.registry,
|
||||
state,
|
||||
None,
|
||||
&dynamic,
|
||||
&mut self.world.random,
|
||||
),
|
||||
};
|
||||
for stack in drops {
|
||||
if &*stack.item != "minecraft:air" && stack.count > 0 {
|
||||
self.pop_resource(at, stack);
|
||||
}
|
||||
}
|
||||
self.pending.clear(at);
|
||||
// BlockBehaviour.spawnAfterBreak with no tool: ores, sculk and spawners
|
||||
// award experience at the block's centre.
|
||||
let name = self.facts.get(state).name.clone();
|
||||
if let Some(xp) = removal::break_experience(&mut self.world.random, &name)
|
||||
&& self.rules.block_drops
|
||||
{
|
||||
let centre = [
|
||||
f64::from(pos.x) + 0.5,
|
||||
f64::from(pos.y) + 0.5,
|
||||
f64::from(pos.z) + 0.5,
|
||||
];
|
||||
self.award_orbs(centre, xp);
|
||||
}
|
||||
}
|
||||
/// `ExperienceOrb.award`: orbs of the largest sizes, each drawing the id
|
||||
/// `tryMergeToExisting` compares from the level random.
|
||||
pub(super) fn award_orbs(&mut self, at: [f64; 3], mut amount: u32) {
|
||||
while amount > 0 {
|
||||
let value = removal::orb_value(amount);
|
||||
amount -= value;
|
||||
let _merge_id = self.world.random.next_int_bound(40);
|
||||
self.spill.orbs.push((at, value));
|
||||
}
|
||||
}
|
||||
/// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block
|
||||
/// entity of `old` at `pos`. A block entity Horizon never created reads as
|
||||
/// vanilla's fresh one: an empty container still draws a spot per slot.
|
||||
pub(super) fn remove_entity(
|
||||
&mut self,
|
||||
pos: BlockPos,
|
||||
old: BlockStateId,
|
||||
side_effects: bool,
|
||||
) -> u8 {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
if self.remove_saved_entity(pos, old, side_effects) {
|
||||
return 0;
|
||||
}
|
||||
// Sculk blocks and creaking hearts notice their removal on their own tick.
|
||||
if matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Sculk(_) | BlockEntity::CreakingHeart(_))
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
let entity = self.world.block_entities.remove(&key);
|
||||
self.world.block_names.remove(&key);
|
||||
let name = self.facts.get(old).name.clone();
|
||||
let kind = removal::pre_remove(&name);
|
||||
let mut neighbour_updates = 0;
|
||||
if side_effects {
|
||||
match kind {
|
||||
PreRemove::Contents { slots, .. } => {
|
||||
let items = entity.as_ref().map_or(&[][..], BlockEntity::slots);
|
||||
for slot in 0..slots {
|
||||
let stack = items.get(slot).cloned().flatten();
|
||||
self.drop_item_stack(pos, stack);
|
||||
}
|
||||
}
|
||||
PreRemove::Campfire => {
|
||||
for _ in 0..4 {
|
||||
self.drop_item_stack(pos, None);
|
||||
}
|
||||
}
|
||||
PreRemove::Jukebox => {
|
||||
// popOutTheItem: removeTheItem stops a playing song (its
|
||||
// events and a neighbour update), the record pops, and
|
||||
// onSongChanged updates the neighbours again.
|
||||
if let Some(BlockEntity::Jukebox(j)) = &entity
|
||||
&& let Some(record) = j.record.clone()
|
||||
{
|
||||
if j.playing {
|
||||
self.jukebox_stopped(pos, old);
|
||||
neighbour_updates += 1;
|
||||
}
|
||||
let at = removal::jukebox_pop_position(&mut self.world.random, pos);
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: record,
|
||||
pos: at,
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
neighbour_updates += 1;
|
||||
}
|
||||
}
|
||||
PreRemove::Lectern => {
|
||||
let props = self.registry.state(old).map(|s| &s.properties);
|
||||
let has_book = props
|
||||
.and_then(|p| p.get("has_book"))
|
||||
.is_some_and(|v| v == "true");
|
||||
let step = match props.and_then(|p| p.get("facing")).map(String::as_str) {
|
||||
Some("north") => [0, -1],
|
||||
Some("south") => [0, 1],
|
||||
Some("west") => [-1, 0],
|
||||
_ => [1, 0],
|
||||
};
|
||||
if has_book
|
||||
&& let Some(BlockEntity::Lectern(l)) = &entity
|
||||
&& let Some(book) = l.book.clone()
|
||||
{
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: book,
|
||||
pos: removal::lectern_book_position(pos, step),
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
}
|
||||
}
|
||||
PreRemove::ShulkerBox
|
||||
| PreRemove::SculkShrieker
|
||||
| PreRemove::CreakingHeart
|
||||
| PreRemove::Beacon
|
||||
| PreRemove::Nothing => {}
|
||||
}
|
||||
}
|
||||
// BlockEntity.setRemoved: a jukebox always reports its song stopping,
|
||||
// a beacon plays its deactivation.
|
||||
match kind {
|
||||
PreRemove::Jukebox => self.jukebox_stopped(pos, old),
|
||||
PreRemove::Beacon => self.events.push(LevelEvent::Sound {
|
||||
pos,
|
||||
sound: "minecraft:block.beacon.deactivate".into(),
|
||||
volume: 1.0,
|
||||
pitch: 1.0,
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(entity) = entity {
|
||||
self.spill.removed.push(([pos.x, pos.y, pos.z], entity));
|
||||
}
|
||||
neighbour_updates
|
||||
}
|
||||
/// The jukebox's `JUKEBOX_STOP_PLAY` game event and level event 1011.
|
||||
fn jukebox_stopped(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
self.events.push(LevelEvent::GameEvent {
|
||||
pos,
|
||||
event: "minecraft:jukebox_stop_play",
|
||||
state: Some(state),
|
||||
});
|
||||
self.events.push(LevelEvent::LevelEvent {
|
||||
id: 1011,
|
||||
pos,
|
||||
data: 0,
|
||||
});
|
||||
}
|
||||
/// A block entity Horizon keeps as it was loaded (campfires, decorated
|
||||
/// pots, chiseled bookshelves, shelves): its items spill as vanilla's do.
|
||||
fn remove_saved_entity(
|
||||
&mut self,
|
||||
pos: BlockPos,
|
||||
old: BlockStateId,
|
||||
side_effects: bool,
|
||||
) -> bool {
|
||||
use horizon_world::nbt::Tag;
|
||||
let chunk_key = (pos.x >> 4, pos.z >> 4);
|
||||
let at = |t: &Tag| {
|
||||
let int = |k: &str| match t.get(k) {
|
||||
Some(Tag::Int(v)) => Some(*v),
|
||||
_ => None,
|
||||
};
|
||||
int("x") == Some(pos.x) && int("y") == Some(pos.y) && int("z") == Some(pos.z)
|
||||
};
|
||||
let Some(chunk) = self.world.chunks.get_mut(&chunk_key) else {
|
||||
return false;
|
||||
};
|
||||
let Some(saved) = chunk.saved.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let Some(index) = saved.block_entities.iter().position(at) else {
|
||||
return false;
|
||||
};
|
||||
let chunk = std::sync::Arc::make_mut(chunk);
|
||||
let Some(saved) = chunk.saved.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let tag = std::sync::Arc::make_mut(saved).block_entities.remove(index);
|
||||
if !side_effects {
|
||||
return true;
|
||||
}
|
||||
let name = self.facts.get(old).name.clone();
|
||||
let items = match removal::pre_remove(&name) {
|
||||
PreRemove::Contents { slots, .. } if &*name == "minecraft:decorated_pot" => {
|
||||
let mut items = vec![None; slots];
|
||||
items[0] = tag
|
||||
.get("item")
|
||||
.and_then(horizon_client::save::item_from_nbt);
|
||||
items
|
||||
}
|
||||
PreRemove::Contents { slots, .. } => {
|
||||
horizon_client::save::decode_items(tag.get("Items"), slots)
|
||||
}
|
||||
PreRemove::Campfire => horizon_client::save::decode_items(tag.get("Items"), 4),
|
||||
_ => return true,
|
||||
};
|
||||
for stack in items {
|
||||
self.drop_item_stack(pos, stack);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `Containers.dropItemStack` of one slot (an empty one still draws its spot).
|
||||
fn drop_item_stack(&mut self, pos: BlockPos, stack: Option<ItemStack>) {
|
||||
let count = stack.as_ref().map_or(0, |s| s.count);
|
||||
for piece in removal::drop_item_stack(&mut self.world.random, pos, count) {
|
||||
let Some(stack) = &stack else { break };
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: ItemStack {
|
||||
count: piece.count,
|
||||
..stack.clone()
|
||||
},
|
||||
pos: piece.pos,
|
||||
motion: Some(piece.motion),
|
||||
delay: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Add the item entities the block behaviour spawned and follow up on the
|
||||
/// block entities it removed.
|
||||
pub(super) fn flush_spill(&mut self) {
|
||||
if self.spill.spawns.is_empty()
|
||||
&& self.spill.removed.is_empty()
|
||||
&& self.spill.orbs.is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let spill = std::mem::take(&mut self.spill);
|
||||
for s in spill.spawns {
|
||||
let motion = s.motion.unwrap_or_else(new_item_motion);
|
||||
self.spawn_item(s.stack, s.pos, motion, s.delay);
|
||||
}
|
||||
for (at, value) in spill.orbs {
|
||||
self.add_orb(at, value);
|
||||
}
|
||||
for (pos, entity) in spill.removed {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if matches!(entity, BlockEntity::Jukebox(_)) {
|
||||
self.jukebox_removed(pos);
|
||||
}
|
||||
if self.container == Some(key) {
|
||||
self.container_opener_event(key, false);
|
||||
self.container = None;
|
||||
self.screen = Screen::Playing;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,7 +447,8 @@ impl Game<'_> {
|
||||
Kind::Merchant => super::trading::update(&mut s, items),
|
||||
Kind::Beacon => {}
|
||||
Kind::Cartography => s.result = self.cartography_result(&s),
|
||||
Kind::Loom => self.loom_changed(&mut s),
|
||||
// The menu engine keeps the loom's state (Game::menu_session).
|
||||
Kind::Loom => {}
|
||||
Kind::Stonecutter => {
|
||||
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
|
||||
if item != s.input_item {
|
||||
@@ -522,7 +523,7 @@ impl Game<'_> {
|
||||
match s.kind {
|
||||
Kind::Enchanting if i == 0 => (true, 1),
|
||||
Kind::Beacon => (super::beacon::is_payment(&stack.item), 1),
|
||||
Kind::Loom => self.loom_slot_rules(i, stack),
|
||||
Kind::Loom => (false, 64),
|
||||
Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64),
|
||||
Kind::Cartography => (
|
||||
matches!(
|
||||
@@ -644,12 +645,8 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
let player = Self::player_slots();
|
||||
let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom);
|
||||
let moved = if (300..305).contains(&slot) || slot >= INPUT {
|
||||
// LoomMenu moves into the inventory front to back, the others back to front.
|
||||
self.move_to(&mut stack, &player, !loom)
|
||||
} else if loom {
|
||||
self.loom_quick_move(slot, &mut stack)
|
||||
self.move_to(&mut stack, &player, true)
|
||||
} else if self.brewing_open() {
|
||||
// BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half.
|
||||
let data = self.data();
|
||||
@@ -894,7 +891,7 @@ impl Game<'_> {
|
||||
self.cartography_taken(pos);
|
||||
}
|
||||
}
|
||||
Kind::Loom => self.loom_taken(&mut s),
|
||||
Kind::Loom => {}
|
||||
Kind::Enchanting => {}
|
||||
}
|
||||
self.station = Some(s);
|
||||
@@ -1069,6 +1066,16 @@ impl Game<'_> {
|
||||
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
|
||||
return true;
|
||||
};
|
||||
if self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom) {
|
||||
// LoomMenu clicks run on the verified menu engine.
|
||||
let input = if shift {
|
||||
horizon_client::menu::Input::QuickMove
|
||||
} else {
|
||||
horizon_client::menu::Input::Pickup
|
||||
};
|
||||
self.menu_click(Some(slot), i32::from(right), input);
|
||||
return true;
|
||||
}
|
||||
if slot == RESULT {
|
||||
self.click_result(shift);
|
||||
return true;
|
||||
|
||||
@@ -8,58 +8,6 @@ pub(super) fn is_shulker_box(name: &str) -> bool {
|
||||
name.ends_with("shulker_box")
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// Block-entity contents on removal: shulker boxes keep theirs for the
|
||||
/// dropped box (`copy_components`), other containers spill them.
|
||||
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
|
||||
if let Some(name) = self
|
||||
.world
|
||||
.block_names
|
||||
.remove(&(pos[0], pos[1], pos[2]))
|
||||
.filter(|_| !matches!(entity, BlockEntity::Banner(_)))
|
||||
{
|
||||
self.pending_names.insert(pos, (block.to_owned(), name));
|
||||
}
|
||||
if let BlockEntity::Banner(banner) = entity {
|
||||
self.pending_banner.insert(pos, banner);
|
||||
return;
|
||||
}
|
||||
if is_shulker_box(block) {
|
||||
if let BlockEntity::Chest(items) = entity {
|
||||
let kept = items
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| Some((i as u8, s?)))
|
||||
.collect();
|
||||
self.pending_shulker.insert(pos, kept);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for stack in entity.contents() {
|
||||
self.pop_resource(pos, stack);
|
||||
}
|
||||
}
|
||||
/// The contents a shulker box dropped at `pos` carries.
|
||||
pub(super) fn attach_shulker_contents(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if !is_shulker_box(&stack.item) {
|
||||
return;
|
||||
}
|
||||
if let Some(contents) = self.pending_shulker.remove(&pos)
|
||||
&& !contents.is_empty()
|
||||
{
|
||||
stack.data_mut().container = contents;
|
||||
}
|
||||
}
|
||||
/// The custom name a broken container drops with (`copy_components`).
|
||||
pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if self
|
||||
.pending_names
|
||||
.get(&pos)
|
||||
.is_some_and(|(item, _)| **item == *stack.item)
|
||||
&& let Some((_, name)) = self.pending_names.remove(&pos)
|
||||
{
|
||||
stack.data_mut().custom_name = Some(name);
|
||||
}
|
||||
}
|
||||
/// A placed container takes the item's custom name.
|
||||
pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
|
||||
@@ -1,52 +1,58 @@
|
||||
//! The subtitle overlay in the game (`Hud` -> `SubtitleOverlay`): sounds the
|
||||
//! audio engine plays feed it, the HUD draws it.
|
||||
//! The subtitle overlay in the game (`Hud` -> `SubtitleOverlay`): the sound
|
||||
//! engine reports the sounds it plays while the overlay listens, the HUD
|
||||
//! renders it (which starts or stops the listening as the "Show Subtitles"
|
||||
//! option says).
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
hud::HudBatch,
|
||||
subtitles::{self, SubtitleOverlay},
|
||||
hud_layout,
|
||||
hud_overlays::{SubtitleFrame, SubtitleOverlay, now_ms},
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SubtitleState {
|
||||
overlay: SubtitleOverlay,
|
||||
listening: bool,
|
||||
overlay: RefCell<SubtitleOverlay>,
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// Feed the sounds played since the last tick to the overlay while the
|
||||
/// `showSubtitles` option is on.
|
||||
/// Feed the sounds the engine reported since the last tick
|
||||
/// (`SoundEventListener.onPlaySound`) while the overlay listens.
|
||||
pub(super) fn tick_subtitles(&mut self) {
|
||||
let on = self.settings.show_subtitles;
|
||||
self.audio.record_heard = on;
|
||||
if !on {
|
||||
if self.subtitles.listening {
|
||||
self.subtitles.listening = false;
|
||||
self.subtitles.overlay.clear();
|
||||
}
|
||||
self.audio.take_heard();
|
||||
let mut overlay = self.subtitles.overlay.borrow_mut();
|
||||
let listening = overlay.listening();
|
||||
self.audio.record_heard = listening;
|
||||
let heard = self.audio.take_heard();
|
||||
if !listening {
|
||||
return;
|
||||
}
|
||||
self.subtitles.listening = true;
|
||||
let now = subtitles::now_ms();
|
||||
let listener = self.audio.listener;
|
||||
for heard in self.audio.take_heard() {
|
||||
self.subtitles.overlay.on_play(&heard, listener, now);
|
||||
let now = now_ms();
|
||||
for h in heard {
|
||||
let at = h.at.unwrap_or(self.audio.listener);
|
||||
overlay.on_play(Some(&h.subtitle), at, h.range, h.looping, now);
|
||||
}
|
||||
self.subtitles
|
||||
.overlay
|
||||
.purge(f64::from(self.settings.notification_display_time), now);
|
||||
}
|
||||
pub(super) fn draw_subtitles(&self, batch: &mut HudBatch) {
|
||||
if !self.settings.show_subtitles {
|
||||
// Hud.extractRenderState: hidden with the rest of the HUD (F1).
|
||||
if self.ui.hide_gui {
|
||||
return;
|
||||
}
|
||||
self.subtitles.overlay.draw(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
self.audio.listener,
|
||||
self.yaw,
|
||||
self.pitch,
|
||||
f64::from(self.settings.notification_display_time),
|
||||
subtitles::now_ms(),
|
||||
);
|
||||
let v = &self.view;
|
||||
let frame = SubtitleFrame {
|
||||
show: self.settings.show_subtitles,
|
||||
position: v.position,
|
||||
forward: v.forwards.map(f64::from),
|
||||
up: v.up.map(f64::from),
|
||||
multiplier: f64::from(self.settings.notification_display_time),
|
||||
background: self.settings.text_background(0.8),
|
||||
width: batch.width as i32,
|
||||
height: batch.height as i32,
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let draws = self
|
||||
.subtitles
|
||||
.overlay
|
||||
.borrow_mut()
|
||||
.extract(&frame, &atlas.font, now_ms());
|
||||
hud_layout::paint(batch, atlas, &draws);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct Frame<'a> {
|
||||
pub hand: &'a [Vertex],
|
||||
/// Full-screen camera effects drawn over the world and hand, under the HUD.
|
||||
pub screen: &'a [crate::screen_effects::ScreenQuad],
|
||||
/// The world border wall, when near enough to be drawn.
|
||||
pub border: Option<BorderDraw>,
|
||||
pub game_time: f32,
|
||||
/// `GlobalSettingsUniform` GameTime: (game time % 24000 + partial tick) / 24000.
|
||||
pub shader_game_time: f32,
|
||||
@@ -95,6 +97,22 @@ pub struct Frame<'a> {
|
||||
/// Torch flicker added to the block light factor of 1.4.
|
||||
pub block_flicker: f32,
|
||||
}
|
||||
/// One frame of the world border wall (`WorldBorderRenderer.render`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BorderDraw {
|
||||
/// The cached wall buffer; uploaded only when `rebuilt`.
|
||||
pub vertices: [crate::border_render::BorderVertex; 16],
|
||||
pub rebuilt: bool,
|
||||
pub transforms: crate::border_render::BorderTransforms,
|
||||
/// Walls to draw (indices of four-vertex quads), nearest first.
|
||||
pub sides: Vec<usize>,
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct BorderUniform {
|
||||
color: [f32; 4],
|
||||
offset: [f32; 4],
|
||||
}
|
||||
pub struct Renderer {
|
||||
instance: wgpu::Instance,
|
||||
surface: wgpu::Surface<'static>,
|
||||
@@ -111,6 +129,11 @@ pub struct Renderer {
|
||||
additive_pipeline: wgpu::RenderPipeline,
|
||||
celestial_pipeline: wgpu::RenderPipeline,
|
||||
celestial_buffer: wgpu::Buffer,
|
||||
/// `RenderPipelines.WORLD_BORDER` and its buffers.
|
||||
border_pipeline: wgpu::RenderPipeline,
|
||||
border_group: wgpu::BindGroup,
|
||||
border_uniform: wgpu::Buffer,
|
||||
border_vertices: wgpu::Buffer,
|
||||
/// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines.
|
||||
screen_pipelines: [wgpu::RenderPipeline; 2],
|
||||
screen_buffer: wgpu::Buffer,
|
||||
@@ -199,6 +222,7 @@ impl Renderer {
|
||||
layers: u32,
|
||||
animations: &[SpriteAnimation],
|
||||
hud_atlas: (&[u8], u32, u32),
|
||||
forcefield: (&[u8], u32),
|
||||
) -> Result<Self> {
|
||||
let instance =
|
||||
wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
|
||||
@@ -773,6 +797,175 @@ impl Renderer {
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
// WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture
|
||||
// (repeat, linear minification with mipmaps, nearest magnification).
|
||||
let (forcefield_pixels, forcefield_size) = forcefield;
|
||||
let (forcefield_mips, forcefield_levels) = mip_chain(forcefield_pixels, forcefield_size, 1);
|
||||
let forcefield_texture = device.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("Forcefield"),
|
||||
size: wgpu::Extent3d {
|
||||
width: forcefield_size,
|
||||
height: forcefield_size,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: forcefield_levels,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
&forcefield_mips,
|
||||
);
|
||||
let forcefield_view = forcefield_texture.create_view(&Default::default());
|
||||
let forcefield_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Forcefield"),
|
||||
address_mode_u: wgpu::AddressMode::Repeat,
|
||||
address_mode_v: wgpu::AddressMode::Repeat,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mag_filter: wgpu::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu::MipmapFilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
let border_uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("World border"),
|
||||
size: std::mem::size_of::<BorderUniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let border_vertices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("World border vertices"),
|
||||
size: 16 * std::mem::size_of::<crate::border_render::BorderVertex>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let border_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("World border bindings"),
|
||||
entries: &[
|
||||
entry(
|
||||
0,
|
||||
vf,
|
||||
wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
),
|
||||
entry(
|
||||
1,
|
||||
vf,
|
||||
wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
),
|
||||
entry(
|
||||
2,
|
||||
vf,
|
||||
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
),
|
||||
entry(
|
||||
3,
|
||||
vf,
|
||||
wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
),
|
||||
],
|
||||
});
|
||||
let border_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("World border resources"),
|
||||
layout: &border_bindings,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: globals.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&forcefield_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&forcefield_sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: border_uniform.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let border_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("World border layout"),
|
||||
bind_group_layouts: &[Some(&border_bindings)],
|
||||
..Default::default()
|
||||
});
|
||||
let border_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon world border"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("border.wgsl").into()),
|
||||
});
|
||||
let border_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2];
|
||||
// RenderPipelines.WORLD_BORDER: BlendFunction.OVERLAY, no culling,
|
||||
// depth writes with a polygon offset of 3 towards the camera.
|
||||
let border_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("World border"),
|
||||
layout: Some(&border_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &border_shader,
|
||||
entry_point: Some("vs_border"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<crate::border_render::BorderVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &border_attributes,
|
||||
})],
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::LessEqual),
|
||||
stencil: Default::default(),
|
||||
bias: wgpu::DepthBiasState {
|
||||
constant: -3,
|
||||
slope_scale: -3.0,
|
||||
clamp: 0.0,
|
||||
},
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &border_shader,
|
||||
entry_point: Some("fs_border"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: config.format.remove_srgb_suffix(),
|
||||
blend: Some(wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::One,
|
||||
dst_factor: wgpu::BlendFactor::Zero,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
}),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let screen_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon screen effects"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()),
|
||||
@@ -864,6 +1057,10 @@ impl Renderer {
|
||||
additive_pipeline,
|
||||
celestial_pipeline,
|
||||
celestial_buffer,
|
||||
border_pipeline,
|
||||
border_group,
|
||||
border_uniform,
|
||||
border_vertices,
|
||||
screen_pipelines,
|
||||
screen_buffer,
|
||||
screen_capacity,
|
||||
@@ -1432,6 +1629,27 @@ impl Renderer {
|
||||
self.index_quads = (entity_quads + additive_quads + hand_quads).next_power_of_two();
|
||||
self.indices = Self::quad_indices(&self.device, self.index_quads);
|
||||
}
|
||||
if let Some(b) = &frame.border {
|
||||
if b.rebuilt {
|
||||
self.queue.write_buffer(
|
||||
&self.border_vertices,
|
||||
0,
|
||||
bytemuck::cast_slice(&b.vertices),
|
||||
);
|
||||
}
|
||||
let t = &b.transforms;
|
||||
let uniform = BorderUniform {
|
||||
color: t.color,
|
||||
offset: [
|
||||
t.model_offset[0],
|
||||
t.model_offset[1],
|
||||
t.model_offset[2],
|
||||
t.texture_offset,
|
||||
],
|
||||
};
|
||||
self.queue
|
||||
.write_buffer(&self.border_uniform, 0, bytemuck::bytes_of(&uniform));
|
||||
}
|
||||
let view_target = surface_frame
|
||||
.texture
|
||||
.create_view(&wgpu::TextureViewDescriptor {
|
||||
@@ -1548,6 +1766,18 @@ impl Renderer {
|
||||
i as u32..i as u32 + 1,
|
||||
);
|
||||
}
|
||||
// LevelRenderer: the world border after translucent terrain and weather.
|
||||
if let Some(b) = frame.border.as_ref().filter(|_| !frame.title) {
|
||||
pass.set_pipeline(&self.border_pipeline);
|
||||
pass.set_bind_group(0, &self.border_group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.border_vertices.slice(..));
|
||||
for &side in &b.sides {
|
||||
let first = side as u32 * 6;
|
||||
pass.draw_indexed(first..first + 6, 0, 0..1);
|
||||
}
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
}
|
||||
if hand_quads > 0 {
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
//! timers of `Hud.tick`), the selected item name (`extractSelectedItemName`
|
||||
//! and its `toolHighlightTimer`), boss bars (`BossHealthOverlay`), the jump
|
||||
//! bar (`JumpableVehicleBar`), the scoreboard sidebar, item decorations
|
||||
//! (`GuiGraphicsExtractor.itemDecorations`), the camera overlays and the
|
||||
//! sleep overlay.
|
||||
//! (`GuiGraphicsExtractor.itemDecorations`), the camera overlays, the
|
||||
//! sleep overlay and the subtitles (`SubtitleOverlay`).
|
||||
use crate::{
|
||||
font::Font,
|
||||
hud_layout::{
|
||||
@@ -897,3 +897,328 @@ pub fn sleep_overlay(w: i32, h: i32, sleep_timer: i32) -> Vec<GuiDraw> {
|
||||
let color = (((220.0 * amount) as i32) << 24) as u32 | 0x10_1020;
|
||||
vec![fill(0, 0, w, h, color)]
|
||||
}
|
||||
|
||||
// ---- subtitles (`SubtitleOverlay`) ------------------------------------------
|
||||
//
|
||||
// Closed captions for the sounds the player could hear, with direction arrows
|
||||
// and a fade over the notification display time. Like vanilla, the overlay
|
||||
// listens to the sound engine only from the frame that renders it with the
|
||||
// "Show Subtitles" option on until a frame renders with it off; turning it
|
||||
// off keeps the captions it has (they show again if the option comes back
|
||||
// before they expire).
|
||||
|
||||
/// `SubtitleOverlay.DISPLAY_TIME` (milliseconds).
|
||||
const DISPLAY_TIME: i64 = 3000;
|
||||
/// `LOOPING_DISPLAY_FULL_BRIGHTNESS_TIME`: looping sounds stay at full brightness this long.
|
||||
const LOOPING_FULL_BRIGHTNESS: i64 = 500;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct PlayedAt {
|
||||
location: [f64; 3],
|
||||
time: i64,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct Subtitle {
|
||||
/// The translation key of the sound event's subtitle (`Component.translatable`).
|
||||
key: String,
|
||||
range: f32,
|
||||
played: Vec<PlayedAt>,
|
||||
looping: bool,
|
||||
}
|
||||
fn distance_sqr(a: [f64; 3], b: [f64; 3]) -> f64 {
|
||||
let (dx, dy, dz) = (a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
||||
dx * dx + dy * dy + dz * dz
|
||||
}
|
||||
/// `Vec3.closerThan(pos, distance)`.
|
||||
fn closer_than(a: [f64; 3], b: [f64; 3], range: f32) -> bool {
|
||||
let r = f64::from(range);
|
||||
distance_sqr(a, b) < r * r
|
||||
}
|
||||
/// `Vec3.equals`: `Double.compare` on each axis.
|
||||
fn same_location(a: [f64; 3], b: [f64; 3]) -> bool {
|
||||
let bits = |v: f64| {
|
||||
if v.is_nan() {
|
||||
f64::NAN.to_bits()
|
||||
} else {
|
||||
v.to_bits()
|
||||
}
|
||||
};
|
||||
(0..3).all(|i| bits(a[i]) == bits(b[i]))
|
||||
}
|
||||
impl Subtitle {
|
||||
/// `getBestSubtitleCandidate`: the only play, else the latest in range
|
||||
/// (the farthest of equally recent ones; the first among full ties).
|
||||
fn best_candidate(&self, position: [f64; 3]) -> Option<PlayedAt> {
|
||||
match self.played.as_slice() {
|
||||
[] => None,
|
||||
[only] => Some(*only),
|
||||
many => many
|
||||
.iter()
|
||||
.filter(|p| closer_than(p.location, position, self.range))
|
||||
.fold(None, |best: Option<PlayedAt>, p| match best {
|
||||
Some(b)
|
||||
if b.time > p.time
|
||||
|| b.time == p.time
|
||||
&& distance_sqr(b.location, position).sqrt()
|
||||
>= distance_sqr(p.location, position).sqrt() =>
|
||||
{
|
||||
Some(b)
|
||||
}
|
||||
_ => Some(*p),
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn refresh(&mut self, location: [f64; 3], now: i64) {
|
||||
self.played.retain(|p| !same_location(location, p.location));
|
||||
self.played.push(PlayedAt {
|
||||
location,
|
||||
time: now,
|
||||
});
|
||||
}
|
||||
fn audible_from(&self, camera: [f64; 3]) -> bool {
|
||||
if self.range.is_infinite() {
|
||||
return true;
|
||||
}
|
||||
self.best_candidate(camera)
|
||||
.is_some_and(|p| closer_than(camera, p.location, self.range))
|
||||
}
|
||||
fn purge_old_instances(&mut self, max_age: f64, now: i64) {
|
||||
self.played.retain(|p| ((now - p.time) as f64) <= max_age);
|
||||
}
|
||||
/// `getBrightness`: fades from 255 to 75 over the display time.
|
||||
fn brightness(&self, at: PlayedAt, multiplier: f64, now: i64) -> i32 {
|
||||
let full = if self.looping {
|
||||
LOOPING_FULL_BRIGHTNESS
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let age = (now - at.time - full).max(0) as f32;
|
||||
let t = age / (((DISPLAY_TIME - full) as f64) * multiplier) as f32;
|
||||
let v = if t < 0.0 {
|
||||
255.0
|
||||
} else if t > 1.0 {
|
||||
75.0
|
||||
} else {
|
||||
255.0 + t * (75.0 - 255.0_f32)
|
||||
};
|
||||
v.floor() as i32
|
||||
}
|
||||
}
|
||||
|
||||
/// What a frame needs to render the overlay: the sound listener, the
|
||||
/// accessibility options and the GUI size.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SubtitleFrame {
|
||||
/// `options.showSubtitles`.
|
||||
pub show: bool,
|
||||
/// `SoundManager.getListenerTransform`: position, forward and up.
|
||||
pub position: [f64; 3],
|
||||
pub forward: [f64; 3],
|
||||
pub up: [f64; 3],
|
||||
/// `options.notificationDisplayTime`.
|
||||
pub multiplier: f64,
|
||||
/// `options.getBackgroundColor(0.8F)` (ARGB, `Settings::text_background`).
|
||||
pub background: u32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
/// Milliseconds on a monotonic clock (`Util.getMillis`).
|
||||
pub fn now_ms() -> i64 {
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
START
|
||||
.get_or_init(std::time::Instant::now)
|
||||
.elapsed()
|
||||
.as_millis() as i64
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct SubtitleOverlay {
|
||||
subtitles: Vec<Subtitle>,
|
||||
listening: bool,
|
||||
}
|
||||
impl SubtitleOverlay {
|
||||
/// Whether the overlay is one of the sound engine's listeners.
|
||||
pub fn listening(&self) -> bool {
|
||||
self.listening
|
||||
}
|
||||
/// `onPlaySound` for a sound the engine played while the overlay listens:
|
||||
/// a subtitle already listed (by its text) refreshes its location.
|
||||
pub fn on_play(
|
||||
&mut self,
|
||||
subtitle: Option<&str>,
|
||||
location: [f64; 3],
|
||||
range: f32,
|
||||
looping: bool,
|
||||
now: i64,
|
||||
) {
|
||||
let Some(key) = subtitle else {
|
||||
return;
|
||||
};
|
||||
if let Some(s) = self.subtitles.iter_mut().find(|s| s.key == key) {
|
||||
s.refresh(location, now);
|
||||
return;
|
||||
}
|
||||
self.subtitles.push(Subtitle {
|
||||
key: key.to_owned(),
|
||||
range,
|
||||
played: vec![PlayedAt {
|
||||
location,
|
||||
time: now,
|
||||
}],
|
||||
looping,
|
||||
});
|
||||
}
|
||||
/// `extractRenderState`: starts or stops listening as the option says,
|
||||
/// forgets old plays and lays out the boxes at the bottom right.
|
||||
pub fn extract(&mut self, frame: &SubtitleFrame, font: &Font, now: i64) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
if self.listening != frame.show {
|
||||
self.listening = frame.show;
|
||||
}
|
||||
if !self.listening {
|
||||
return out;
|
||||
}
|
||||
let position = frame.position;
|
||||
let (f, u) = (frame.forward, frame.up);
|
||||
// ListenerTransform.right: forward x up.
|
||||
let right = [
|
||||
f[1] * u[2] - f[2] * u[1],
|
||||
f[2] * u[0] - f[0] * u[2],
|
||||
f[0] * u[1] - f[1] * u[0],
|
||||
];
|
||||
let width_of = |t: &Text| width(font, t);
|
||||
let mut audible = Vec::new();
|
||||
let mut width = 0;
|
||||
for (i, s) in self.subtitles.iter_mut().enumerate() {
|
||||
if !s.played.is_empty() {
|
||||
s.purge_old_instances(3000.0 * frame.multiplier, now);
|
||||
}
|
||||
if s.audible_from(position) && !s.played.is_empty() {
|
||||
width = width.max(width_of(&Text::translate(&s.key, &[])));
|
||||
audible.push(i);
|
||||
}
|
||||
}
|
||||
if audible.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let w = |s: &str| font.width(s) as i32;
|
||||
width += w("<") + w(" ") + w(">") + w(" ");
|
||||
let mut row = 0;
|
||||
for i in audible {
|
||||
let s = &self.subtitles[i];
|
||||
let text_value = Text::translate(&s.key, &[]);
|
||||
let Some(closest) = s.best_candidate(position) else {
|
||||
continue;
|
||||
};
|
||||
let mut delta = [
|
||||
closest.location[0] - position[0],
|
||||
closest.location[1] - position[1],
|
||||
closest.location[2] - position[2],
|
||||
];
|
||||
// Vec3.normalize.
|
||||
let length = distance_sqr(delta, [0.0; 3]).sqrt();
|
||||
delta = if length < f64::from(1.0e-5_f32) {
|
||||
[0.0; 3]
|
||||
} else {
|
||||
delta.map(|v| v / length)
|
||||
};
|
||||
let dot = |a: [f64; 3]| a[0] * delta[0] + a[1] * delta[1] + a[2] * delta[2];
|
||||
let (rightness, forwardness) = (dot(right), dot(f));
|
||||
let in_view = forwardness > 0.5;
|
||||
let half_width = width / 2;
|
||||
let height = 9;
|
||||
let half_height = height / 2;
|
||||
let text_width = width_of(&text_value);
|
||||
let brightness = s.brightness(closest, frame.multiplier, now);
|
||||
out.push(GuiDraw::Push(vec![
|
||||
PoseOp::Translate(
|
||||
frame.width as f32 - half_width as f32 * 1.0 - 2.0,
|
||||
(frame.height - 35) as f32 - (row * (height + 1)) as f32 * 1.0,
|
||||
),
|
||||
PoseOp::Scale(1.0, 1.0),
|
||||
]));
|
||||
out.push(fill(
|
||||
-half_width - 1,
|
||||
-half_height - 1,
|
||||
half_width + 1,
|
||||
half_height + 1,
|
||||
frame.background,
|
||||
));
|
||||
let b = brightness as u32 & 0xFF;
|
||||
let color = 0xFF00_0000 | b << 16 | b << 8 | b;
|
||||
if !in_view {
|
||||
if rightness > 0.0 {
|
||||
text(
|
||||
&mut out,
|
||||
Text::literal(">"),
|
||||
half_width - w(">"),
|
||||
-half_height,
|
||||
color,
|
||||
true,
|
||||
);
|
||||
} else if rightness < 0.0 {
|
||||
text(
|
||||
&mut out,
|
||||
Text::literal("<"),
|
||||
-half_width,
|
||||
-half_height,
|
||||
color,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
text(
|
||||
&mut out,
|
||||
text_value,
|
||||
-text_width / 2,
|
||||
-half_height,
|
||||
color,
|
||||
true,
|
||||
);
|
||||
out.push(GuiDraw::Pop);
|
||||
row += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod subtitle_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn candidates_and_brightness() {
|
||||
let mut s = Subtitle {
|
||||
key: "a".into(),
|
||||
range: 16.0,
|
||||
played: vec![PlayedAt {
|
||||
location: [0.0, 0.0, 3.0],
|
||||
time: 1000,
|
||||
}],
|
||||
looping: false,
|
||||
};
|
||||
assert_eq!(s.brightness(s.played[0], 1.0, 1000), 255);
|
||||
assert_eq!(s.brightness(s.played[0], 1.0, 2500), 165);
|
||||
assert_eq!(s.brightness(s.played[0], 2.0, 2500), 210);
|
||||
assert_eq!(s.brightness(s.played[0], 1.0, 9000), 75);
|
||||
// Equally recent plays: the farthest in range wins.
|
||||
s.refresh([0.0, 0.0, 5.0], 1000);
|
||||
s.refresh([0.0, 0.0, 40.0], 1000);
|
||||
let best = s.best_candidate([0.0; 3]).unwrap();
|
||||
assert_eq!(best.location, [0.0, 0.0, 5.0]);
|
||||
s.purge_old_instances(3000.0, 4001);
|
||||
assert!(s.played.is_empty());
|
||||
assert!(!s.audible_from([0.0; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listening_follows_the_option() {
|
||||
let mut o = SubtitleOverlay::default();
|
||||
o.on_play(Some("a"), [0.0; 3], 16.0, false, 0);
|
||||
assert_eq!(o.subtitles.len(), 1);
|
||||
o.on_play(None, [0.0; 3], 16.0, false, 0);
|
||||
o.on_play(Some("a"), [1.0; 3], 16.0, false, 5);
|
||||
assert_eq!(o.subtitles.len(), 1);
|
||||
assert_eq!(o.subtitles[0].played.len(), 2);
|
||||
assert!(!o.listening());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,8 +520,11 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
|
||||
let mut fields = vec![
|
||||
("title", raw(Tag::String(w.title.as_str().into()))),
|
||||
("author", Tag::String(w.author.as_str().into())),
|
||||
("pages", Tag::List(pages)),
|
||||
];
|
||||
// `optionalFieldOf("pages", List.of())`: no pages, no field.
|
||||
if !w.pages.is_empty() {
|
||||
fields.push(("pages", Tag::List(pages)));
|
||||
}
|
||||
if w.generation != 0 {
|
||||
fields.push(("generation", Tag::Int(i32::from(w.generation))));
|
||||
}
|
||||
|
||||
@@ -158,6 +158,8 @@ pub struct ItemStack {
|
||||
/// Components beyond count and damage (see `item_data`); None when default.
|
||||
pub extra: Option<Box<crate::item_data::StackData>>,
|
||||
}
|
||||
/// Item ids standing for a loot table's `minecraft:dynamic` entries.
|
||||
const DYNAMIC: &str = "#dynamic:";
|
||||
pub struct Items {
|
||||
pub items: HashMap<Arc<str>, ItemInfo>,
|
||||
pub order: Vec<Arc<str>>,
|
||||
@@ -575,6 +577,53 @@ impl Items {
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut R,
|
||||
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
|
||||
) -> Vec<ItemStack> {
|
||||
self.block_drops_full(registry, state, held, &[], random, sequences)
|
||||
}
|
||||
/// `block_drops` with the block entity's dynamic drops (`LootParams.withDynamicDrop`:
|
||||
/// a decorated pot's sherds) in place of the `minecraft:dynamic` entries.
|
||||
pub fn block_drops_with(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
dynamic: &[ItemStack],
|
||||
random: &mut impl RandomSource,
|
||||
) -> Vec<ItemStack> {
|
||||
self.block_drops_full(registry, state, held, dynamic, random, None)
|
||||
}
|
||||
/// `block_drops_in` with dynamic drops.
|
||||
pub fn block_drops_full(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
dynamic: &[ItemStack],
|
||||
random: &mut impl RandomSource,
|
||||
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
|
||||
) -> Vec<ItemStack> {
|
||||
let drops = self.block_drops_raw(registry, state, held, random, sequences);
|
||||
if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) {
|
||||
return drops;
|
||||
}
|
||||
drops
|
||||
.into_iter()
|
||||
.flat_map(|d| {
|
||||
if d.item.starts_with(DYNAMIC) {
|
||||
dynamic.to_vec()
|
||||
} else {
|
||||
vec![d]
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn block_drops_raw(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut impl RandomSource,
|
||||
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
|
||||
) -> Vec<ItemStack> {
|
||||
let Some(block) = registry.state(state) else {
|
||||
return vec![];
|
||||
@@ -944,6 +993,21 @@ impl LootContext<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
// DynamicLoot: what the block entity adds (a cracked decorated
|
||||
// pot's sherds), filled in by `block_drops_with`.
|
||||
"minecraft:dynamic" => {
|
||||
out.push((
|
||||
e["weight"].as_i64().unwrap_or(1) as i32,
|
||||
ItemStack {
|
||||
item: Arc::from(format!("{DYNAMIC}{}", e["name"].as_str().unwrap_or(""))),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
Value::Null,
|
||||
));
|
||||
true
|
||||
}
|
||||
"minecraft:empty" => {
|
||||
out.push((
|
||||
e["weight"].as_i64().unwrap_or(1) as i32,
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod block_entity_nbt;
|
||||
pub mod block_entity_render;
|
||||
pub mod block_transform;
|
||||
pub mod blocks;
|
||||
pub mod border_render;
|
||||
pub mod bossbar;
|
||||
pub mod brewing;
|
||||
pub mod camera;
|
||||
@@ -78,6 +79,7 @@ pub mod options_fixes;
|
||||
pub mod options_ui;
|
||||
pub mod packs;
|
||||
pub mod particles;
|
||||
pub mod patrol;
|
||||
pub mod pose;
|
||||
pub mod projectiles;
|
||||
pub mod raid;
|
||||
@@ -87,7 +89,9 @@ pub mod save;
|
||||
pub mod scoreboard;
|
||||
pub mod scoreboard_cmd;
|
||||
pub mod screen_effects;
|
||||
pub mod screen_layout;
|
||||
pub mod sculk;
|
||||
pub mod server;
|
||||
pub mod settings;
|
||||
pub mod shadows;
|
||||
pub mod signs;
|
||||
@@ -100,7 +104,7 @@ pub mod stations;
|
||||
pub mod stopwatches;
|
||||
pub mod streaming;
|
||||
pub mod structure_blocks;
|
||||
pub mod subtitles;
|
||||
pub mod tab_list;
|
||||
pub mod testgen;
|
||||
pub mod text;
|
||||
pub mod title;
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
//! `AbstractContainerMenu.clicked` over vanilla's slot layouts: every
|
||||
//! `ContainerInput` (pickup, quick move, swap, clone, throw, the three quick
|
||||
//! craft drags, pickup all) for the player inventory, the crafting table, the
|
||||
//! chest family, hoppers, dispensers, shulker boxes and the furnaces.
|
||||
//! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing
|
||||
//! stand, the crafter (its client menu and the block entity's server menu with
|
||||
//! `setSlotState`) and the loom (`clickMenuButton`, `slotsChanged`).
|
||||
//! `tools/test_menu_click_parity.py` compares every click with vanilla's menu
|
||||
//! classes.
|
||||
use crate::{
|
||||
banner::{self, Banners},
|
||||
brewing::Brewing,
|
||||
crafting::Recipes,
|
||||
items::{ItemStack, Items},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod place;
|
||||
|
||||
/// What a menu needs to know about items and recipes.
|
||||
pub struct Env<'a> {
|
||||
pub items: &'a Items,
|
||||
pub recipes: &'a Recipes,
|
||||
pub brewing: &'a Brewing,
|
||||
pub banners: &'a Banners,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
@@ -54,7 +61,12 @@ pub enum Kind {
|
||||
/// The cooking recipe type: smelting, blasting or smoking.
|
||||
Furnace(&'static str),
|
||||
Brewing,
|
||||
/// `CrafterMenu` over a plain crafting container (the client's menu).
|
||||
Crafter,
|
||||
/// `CrafterMenu` over the `CrafterBlockEntity` (the server's menu): the
|
||||
/// result follows the grid, and filling a disabled slot enables it.
|
||||
CrafterBlock,
|
||||
Loom,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -73,6 +85,8 @@ impl Kind {
|
||||
"smoker" => Self::Furnace("smoking"),
|
||||
"brewing" => Self::Brewing,
|
||||
"crafter" => Self::Crafter,
|
||||
"crafter_be" => Self::CrafterBlock,
|
||||
"loom" => Self::Loom,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -100,6 +114,12 @@ enum Role {
|
||||
Ingredient,
|
||||
/// `BrewingStandMenu.FuelSlot`.
|
||||
BrewFuel,
|
||||
/// The loom's banner, dye and pattern slots.
|
||||
LoomBanner,
|
||||
LoomDye,
|
||||
LoomPattern,
|
||||
/// The loom's result slot (a plain slot whose `onTake` uses the inputs).
|
||||
LoomResult,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -126,6 +146,8 @@ pub struct Menu {
|
||||
pub carried: Option<ItemStack>,
|
||||
pub data: Vec<i32>,
|
||||
pub creative: bool,
|
||||
/// The selected hotbar slot (`Inventory.selected`).
|
||||
pub selected: usize,
|
||||
/// Dropped stacks (canonical text), `xp+N` and the like, in order.
|
||||
pub drops: Vec<String>,
|
||||
/// The dropped stacks themselves, for the caller to throw.
|
||||
@@ -133,6 +155,12 @@ pub struct Menu {
|
||||
quick_status: i32,
|
||||
quick_type: i32,
|
||||
quick_slots: Vec<usize>,
|
||||
/// `LoomMenu.selectablePatterns`.
|
||||
pub loom_patterns: Vec<Arc<str>>,
|
||||
/// Sounds the menu plays (`ui.loom.take_result`), for the caller.
|
||||
pub sounds: Vec<&'static str>,
|
||||
/// Recipes whose result was taken (`awardUsedRecipes`), for the caller.
|
||||
pub crafted: Vec<String>,
|
||||
}
|
||||
|
||||
fn same_item(a: &ItemStack, b: &ItemStack) -> bool {
|
||||
@@ -238,7 +266,7 @@ impl Menu {
|
||||
slots.extend(main(27, Role::Shulker));
|
||||
player(&mut slots);
|
||||
}
|
||||
Kind::Crafter => {
|
||||
Kind::Crafter | Kind::CrafterBlock => {
|
||||
containers[MAIN] = vec![None; 9];
|
||||
slots.extend(main(9, Role::CrafterIn));
|
||||
player(&mut slots);
|
||||
@@ -249,6 +277,26 @@ impl Menu {
|
||||
});
|
||||
data = 10;
|
||||
}
|
||||
Kind::Loom => {
|
||||
containers[MAIN] = vec![None; 3];
|
||||
for (index, role) in [Role::LoomBanner, Role::LoomDye, Role::LoomPattern]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
slots.push(Slot {
|
||||
container: MAIN,
|
||||
index,
|
||||
role,
|
||||
});
|
||||
}
|
||||
slots.push(Slot {
|
||||
container: RESULT,
|
||||
index: 0,
|
||||
role: Role::LoomResult,
|
||||
});
|
||||
player(&mut slots);
|
||||
data = 1;
|
||||
}
|
||||
Kind::Brewing => {
|
||||
containers[MAIN] = vec![None; 5];
|
||||
for (index, role) in [
|
||||
@@ -303,11 +351,132 @@ impl Menu {
|
||||
carried: None,
|
||||
data: vec![0; data],
|
||||
creative: false,
|
||||
selected: 0,
|
||||
drops: Vec::new(),
|
||||
dropped: Vec::new(),
|
||||
quick_status: 0,
|
||||
quick_type: 0,
|
||||
quick_slots: Vec::new(),
|
||||
loom_patterns: Vec::new(),
|
||||
sounds: Vec::new(),
|
||||
crafted: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> Kind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// `clickMenuButton`: the loom's pattern buttons. False when refused.
|
||||
pub fn button(&mut self, env: &Env, id: i32) -> bool {
|
||||
if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() {
|
||||
return false;
|
||||
}
|
||||
self.data[0] = id;
|
||||
let pattern = self.loom_patterns[id as usize].clone();
|
||||
self.loom_setup_result(env, &pattern);
|
||||
true
|
||||
}
|
||||
|
||||
/// `CrafterBlockEntity.setSlotState` (the slot state packet): only an
|
||||
/// empty slot can be disabled or enabled.
|
||||
pub fn set_slot_state(&mut self, slot: usize, enabled: bool) {
|
||||
if self.kind == Kind::CrafterBlock && slot < 9 && self.containers[MAIN][slot].is_none() {
|
||||
self.data[slot] = i32::from(!enabled);
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu after a fixture set its slots: the block crafter's slot
|
||||
/// listener has refreshed the result (`broadcastChanges`).
|
||||
pub fn settle(&mut self, env: &Env) {
|
||||
if self.kind == Kind::CrafterBlock {
|
||||
self.crafter_result(env);
|
||||
}
|
||||
}
|
||||
|
||||
/// `CrafterMenu.refreshRecipeResult`.
|
||||
fn crafter_result(&mut self, env: &Env) {
|
||||
self.containers[RESULT][0] = env
|
||||
.recipes
|
||||
.find(&self.containers[MAIN], 3)
|
||||
.map(|(_, stack)| stack)
|
||||
.filter(|s| s.count > 0);
|
||||
}
|
||||
|
||||
/// `LoomMenu.setupResultSlot`.
|
||||
fn loom_setup_result(&mut self, env: &Env, pattern: &str) {
|
||||
let mut result = None;
|
||||
if let (Some(banner_stack), Some(dye)) = (
|
||||
self.containers[MAIN][0].as_ref(),
|
||||
self.containers[MAIN][1].as_ref(),
|
||||
) && let Some(color) = env.banners.loom_dye(env.items, dye)
|
||||
{
|
||||
result = Some(banner::loom_result(banner_stack, &color, pattern));
|
||||
}
|
||||
self.containers[RESULT][0] = result;
|
||||
}
|
||||
|
||||
/// `LoomMenu.slotsChanged`.
|
||||
fn loom_changed(&mut self, env: &Env) {
|
||||
let has_inputs = self.containers[MAIN][0].is_some() && self.containers[MAIN][1].is_some();
|
||||
if !has_inputs {
|
||||
self.containers[RESULT][0] = None;
|
||||
self.loom_patterns.clear();
|
||||
self.data[0] = -1;
|
||||
return;
|
||||
}
|
||||
let selected = self.data[0];
|
||||
let valid = selected >= 0 && (selected as usize) < self.loom_patterns.len();
|
||||
let pattern_item = self.containers[MAIN][2].clone();
|
||||
let previous = std::mem::replace(
|
||||
&mut self.loom_patterns,
|
||||
env.banners.selectable(pattern_item.as_ref()),
|
||||
);
|
||||
let shown = if self.loom_patterns.len() == 1 {
|
||||
self.data[0] = 0;
|
||||
Some(self.loom_patterns[0].clone())
|
||||
} else if !valid {
|
||||
self.data[0] = -1;
|
||||
None
|
||||
} else {
|
||||
let value = previous[selected as usize].clone();
|
||||
match self.loom_patterns.iter().position(|p| *p == value) {
|
||||
Some(i) => {
|
||||
self.data[0] = i as i32;
|
||||
Some(value)
|
||||
}
|
||||
None => {
|
||||
self.data[0] = -1;
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
match shown {
|
||||
Some(pattern) => {
|
||||
let full = self.containers[MAIN][0]
|
||||
.as_ref()
|
||||
.is_some_and(banner::has_max_layers);
|
||||
if full {
|
||||
self.data[0] = -1;
|
||||
self.containers[RESULT][0] = None;
|
||||
} else {
|
||||
self.loom_setup_result(env, &pattern);
|
||||
}
|
||||
}
|
||||
None => self.containers[RESULT][0] = None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs,
|
||||
/// the block crafter refreshes its result.
|
||||
fn slot_changed(&mut self, env: &Env, s: usize) {
|
||||
if self.slots[s].container != MAIN {
|
||||
return;
|
||||
}
|
||||
match self.kind {
|
||||
Kind::Loom => self.loom_changed(env),
|
||||
Kind::CrafterBlock => self.crafter_result(env),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,9 +583,18 @@ impl Menu {
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.is_some_and(|i| i.brewing_fuel.is_some()),
|
||||
Role::LoomBanner => Self::is_banner(stack),
|
||||
Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(),
|
||||
Role::LoomPattern => env.banners.is_pattern_item(env.items, stack),
|
||||
Role::LoomResult => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `BannerItem`.
|
||||
fn is_banner(stack: &ItemStack) -> bool {
|
||||
stack.item.ends_with("_banner")
|
||||
}
|
||||
|
||||
fn may_pickup(&self, s: usize) -> bool {
|
||||
match self.slots[s].role {
|
||||
Role::Inert => false,
|
||||
@@ -444,16 +622,34 @@ impl Menu {
|
||||
fn put(&mut self, env: &Env, s: usize, mut stack: Option<ItemStack>) {
|
||||
tidy(&mut stack);
|
||||
let slot = self.slots[s];
|
||||
// SimpleContainer / BaseContainerBlockEntity.setItem: limitSize to
|
||||
// getMaxStackSize(stack). The loom's result is a SimpleContainer too.
|
||||
if (slot.container == MAIN || slot.role == Role::LoomResult)
|
||||
&& let Some(st) = stack.as_mut()
|
||||
{
|
||||
st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st)));
|
||||
}
|
||||
// CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it.
|
||||
if self.kind == Kind::CrafterBlock
|
||||
&& slot.container == MAIN
|
||||
&& self.data[slot.index] == 1
|
||||
&& self.containers[MAIN][slot.index].is_none()
|
||||
{
|
||||
self.data[slot.index] = 0;
|
||||
}
|
||||
self.containers[slot.container][slot.index] = stack;
|
||||
if slot.container == GRID {
|
||||
self.recompute(env);
|
||||
}
|
||||
self.slot_changed(env, s);
|
||||
}
|
||||
|
||||
/// `Slot.remove`: the container's `removeItem`.
|
||||
fn remove(&mut self, env: &Env, s: usize, amount: u32) -> Option<ItemStack> {
|
||||
let slot = self.slots[s];
|
||||
if slot.container == RESULT {
|
||||
// ResultContainer.removeItem takes the whole stack; the loom's result
|
||||
// is a SimpleContainer slot and splits.
|
||||
if slot.container == RESULT && slot.role != Role::LoomResult {
|
||||
return self.containers[RESULT][0].take();
|
||||
}
|
||||
let cell = &mut self.containers[slot.container][slot.index];
|
||||
@@ -465,6 +661,10 @@ impl Menu {
|
||||
if out.is_some() && slot.container == GRID {
|
||||
self.recompute(env);
|
||||
}
|
||||
// SimpleContainer.removeItem calls setChanged when it took something.
|
||||
if out.is_some() && self.kind == Kind::Loom {
|
||||
self.slot_changed(env, s);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -482,11 +682,29 @@ impl Menu {
|
||||
|
||||
/// `ResultSlot.onTake` and the other `Slot.onTake` overrides.
|
||||
fn on_take(&mut self, env: &Env, s: usize) {
|
||||
if self.slots[s].role == Role::LoomResult {
|
||||
// LoomMenu's result onTake: one banner and one dye are used up.
|
||||
self.remove(env, 0, 1);
|
||||
self.remove(env, 1, 1);
|
||||
if self.containers[MAIN][0].is_none() || self.containers[MAIN][1].is_none() {
|
||||
self.data[0] = -1;
|
||||
}
|
||||
self.sounds.push("minecraft:ui.loom.take_result");
|
||||
return;
|
||||
}
|
||||
if matches!(self.kind, Kind::CrafterBlock) && self.slots[s].container == MAIN {
|
||||
// Slot.onTake -> CrafterSlot.setChanged -> the result refresh.
|
||||
self.slot_changed(env, s);
|
||||
return;
|
||||
}
|
||||
if self.slots[s].role != Role::CraftResult {
|
||||
return;
|
||||
}
|
||||
let n = self.grid_size;
|
||||
let grid = self.containers[GRID].clone();
|
||||
if let Some((id, _)) = env.recipes.find(&grid, n) {
|
||||
self.crafted.push(format!("minecraft:{id}"));
|
||||
}
|
||||
let remaining = env
|
||||
.recipes
|
||||
.find(&grid, n)
|
||||
@@ -611,13 +829,16 @@ impl Menu {
|
||||
/// `Inventory.getSlotWithRemainingSpace` (selected slot 0, offhand, rest).
|
||||
fn slot_with_space(&self, env: &Env, stack: &ItemStack) -> Option<usize> {
|
||||
let inv = &self.containers[PLAYER];
|
||||
[0, OFFHAND].into_iter().chain(0..36).find(|&i| {
|
||||
inv[i].as_ref().is_some_and(|have| {
|
||||
have.same_item_same_components(stack)
|
||||
&& Self::stackable(env, have)
|
||||
&& have.count < CONTAINER_MAX.min(Self::max_stack(env, have))
|
||||
[self.selected, OFFHAND]
|
||||
.into_iter()
|
||||
.chain(0..36)
|
||||
.find(|&i| {
|
||||
inv[i].as_ref().is_some_and(|have| {
|
||||
have.same_item_same_components(stack)
|
||||
&& Self::stackable(env, have)
|
||||
&& have.count < CONTAINER_MAX.min(Self::max_stack(env, have))
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `Inventory.addResource`: returns what did not fit.
|
||||
@@ -738,10 +959,12 @@ impl Menu {
|
||||
stack.count = 0;
|
||||
target.count = total;
|
||||
changed = true;
|
||||
self.slot_changed(env, dest);
|
||||
} else if target.count < max {
|
||||
stack.count -= max - target.count;
|
||||
target.count = max;
|
||||
changed = true;
|
||||
self.slot_changed(env, dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -859,7 +1082,44 @@ impl Menu {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Kind::Crafter => {
|
||||
Kind::Loom => {
|
||||
after_take = true;
|
||||
if index == 3 {
|
||||
if !self.move_to(env, &mut stack, 4, 40, true) {
|
||||
return None;
|
||||
}
|
||||
} else if index > 3 {
|
||||
let target = if Self::is_banner(&stack) {
|
||||
Some(0)
|
||||
} else if env.banners.loom_dye(env.items, &stack).is_some() {
|
||||
Some(1)
|
||||
} else if env.banners.is_pattern_item(env.items, &stack) {
|
||||
Some(2)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match target {
|
||||
Some(t) => {
|
||||
if !self.move_to(env, &mut stack, t, t + 1, false) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None if index < 31 => {
|
||||
if !self.move_to(env, &mut stack, 31, 40, false) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if index < 40 && !self.move_to(env, &mut stack, 4, 31, false) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if !self.move_to(env, &mut stack, 4, 40, false) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Kind::Crafter | Kind::CrafterBlock => {
|
||||
after_take = true;
|
||||
if index < 9 {
|
||||
if !self.move_to(env, &mut stack, 9, 45, true) {
|
||||
@@ -961,9 +1221,11 @@ impl Menu {
|
||||
// The stack was edited in place in its slot.
|
||||
let slot = self.slots[index];
|
||||
if stack.count == 0 {
|
||||
self.containers[slot.container][slot.index] = None;
|
||||
self.put(env, index, None);
|
||||
} else {
|
||||
self.containers[slot.container][slot.index] = Some(stack.clone());
|
||||
self.slot_changed(env, index);
|
||||
}
|
||||
if check_count && stack.count == clicked.count {
|
||||
return None;
|
||||
@@ -1173,8 +1435,14 @@ impl Menu {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The PICKUP branch of `doClick` (without the bundle overrides).
|
||||
/// The PICKUP branch of `doClick` (without the bundle overrides), ending
|
||||
/// with `slot.setChanged()`.
|
||||
fn pickup(&mut self, env: &Env, s: usize, primary: bool) {
|
||||
self.pickup_inner(env, s, primary);
|
||||
self.slot_changed(env, s);
|
||||
}
|
||||
|
||||
fn pickup_inner(&mut self, env: &Env, s: usize, primary: bool) {
|
||||
let clicked = self.slot(s).cloned();
|
||||
match clicked {
|
||||
None => {
|
||||
@@ -1312,7 +1580,7 @@ impl Menu {
|
||||
if self.has_item(t)
|
||||
&& self.quick_replace(t, &have, env)
|
||||
&& self.may_pickup(t)
|
||||
&& self.slots[t].container != RESULT
|
||||
&& (self.slots[t].container != RESULT || self.kind == Kind::Loom)
|
||||
{
|
||||
let item = self.slot(t).expect("has item").clone();
|
||||
if pass != 0 || item.count != Self::max_stack(env, &item) {
|
||||
|
||||
@@ -0,0 +1,707 @@
|
||||
//! `ServerPlaceRecipe`: what the server does with a recipe book click
|
||||
//! (`ServerboundPlaceRecipePacket`) in the inventory, crafting table and
|
||||
//! furnace menus, with `StackedContents`' exact matching of items to
|
||||
//! ingredients (`RecipePicker`). `tools/test_place_recipe_parity.py`
|
||||
//! compares every placement with vanilla's.
|
||||
//!
|
||||
//! Vanilla keeps the available items in a `Reference2IntOpenHashMap` keyed by
|
||||
//! item holders, whose iteration order follows their identity hash codes: it
|
||||
//! differs between runs of the game, and decides which of several fitting
|
||||
//! items fills an ingredient. `Stacked` keeps an explicit order: the order
|
||||
//! items were first counted, or one given (the harness passes the oracle's).
|
||||
use super::{Env, GRID, Kind, MAIN, Menu, PLAYER, RESULT, split, tidy};
|
||||
use crate::{
|
||||
crafting::{Ingredient, Placement},
|
||||
items::ItemStack,
|
||||
};
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
/// `StackedContents<Holder<Item>>`: item counts in an iteration order.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Stacked {
|
||||
keys: Vec<Arc<str>>,
|
||||
amounts: Vec<i32>,
|
||||
index: HashMap<Arc<str>, usize>,
|
||||
}
|
||||
|
||||
/// `Inventory.isUsableForCrafting`: not damaged, enchanted or renamed.
|
||||
pub fn usable_for_crafting(stack: &ItemStack) -> bool {
|
||||
stack.damage == 0 && stack.enchantments().is_empty() && stack.custom_name().is_none()
|
||||
}
|
||||
|
||||
impl Stacked {
|
||||
/// `StackedContents.account`.
|
||||
pub fn account(&mut self, item: &Arc<str>, count: i32) {
|
||||
match self.index.get(item) {
|
||||
Some(&i) => self.amounts[i] += count,
|
||||
None => {
|
||||
self.index.insert(item.clone(), self.keys.len());
|
||||
self.keys.push(item.clone());
|
||||
self.amounts.push(count);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `StackedItemContents.accountStack(stack, maxCount)`.
|
||||
pub fn account_stack(&mut self, stack: &ItemStack, max: u32) {
|
||||
if stack.count > 0 {
|
||||
self.account(&stack.item, stack.count.min(max) as i32);
|
||||
}
|
||||
}
|
||||
/// `accountSimpleStack`.
|
||||
pub fn account_simple(&mut self, stack: &ItemStack, max: u32) {
|
||||
if usable_for_crafting(stack) {
|
||||
self.account_stack(stack, max);
|
||||
}
|
||||
}
|
||||
/// Reorders the keys: the given items first, in that order (vanilla's hash
|
||||
/// map order for the same items), then the rest as they were.
|
||||
pub fn set_order(&mut self, order: &[String]) {
|
||||
let mut keys: Vec<Arc<str>> = order
|
||||
.iter()
|
||||
.filter_map(|o| self.index.get_key_value(o.as_str()).map(|(k, _)| k.clone()))
|
||||
.collect();
|
||||
for k in &self.keys {
|
||||
if !keys.contains(k) {
|
||||
keys.push(k.clone());
|
||||
}
|
||||
}
|
||||
let amounts = keys.iter().map(|k| self.amounts[self.index[k]]).collect();
|
||||
self.index = keys
|
||||
.iter()
|
||||
.cloned()
|
||||
.enumerate()
|
||||
.map(|(i, k)| (k, i))
|
||||
.collect();
|
||||
self.keys = keys;
|
||||
self.amounts = amounts;
|
||||
}
|
||||
pub fn keys(&self) -> &[Arc<str>] {
|
||||
&self.keys
|
||||
}
|
||||
/// `canCraft(ingredients, null)` without touching the counts (the recipe
|
||||
/// book's craftable test; the answer does not depend on the order; no
|
||||
/// ingredients at all can always be found).
|
||||
pub fn can_craft(&self, ingredients: &[&Ingredient]) -> bool {
|
||||
self.clone().try_pick(ingredients, 1, None)
|
||||
}
|
||||
/// `getResultUpperBound`.
|
||||
fn upper_bound(&self, ingredients: &[&Ingredient]) -> i32 {
|
||||
let mut min = i32::MAX;
|
||||
'ingredients: for ing in ingredients {
|
||||
let mut max = 0;
|
||||
for (key, &count) in self.keys.iter().zip(&self.amounts) {
|
||||
if count > max {
|
||||
if ing.0.contains(&**key) {
|
||||
max = count;
|
||||
}
|
||||
if max >= min {
|
||||
continue 'ingredients;
|
||||
}
|
||||
}
|
||||
}
|
||||
min = max;
|
||||
if min == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
min
|
||||
}
|
||||
/// `tryPick` (`canCraft(recipe, amount, output)`).
|
||||
pub fn try_pick(
|
||||
&mut self,
|
||||
ingredients: &[&Ingredient],
|
||||
amount: i32,
|
||||
output: Option<&mut Vec<Arc<str>>>,
|
||||
) -> bool {
|
||||
Picker::new(self, ingredients).try_pick(amount, output)
|
||||
}
|
||||
/// `tryPickAll` (`getBiggestCraftableStack`).
|
||||
pub fn try_pick_all(
|
||||
&mut self,
|
||||
ingredients: &[&Ingredient],
|
||||
max_size: i32,
|
||||
output: Option<&mut Vec<Arc<str>>>,
|
||||
) -> i32 {
|
||||
Picker::new(self, ingredients).try_pick_all(max_size, output)
|
||||
}
|
||||
}
|
||||
|
||||
/// `StackedContents.RecipePicker`: augmenting paths over item-ingredient pairs.
|
||||
struct Picker<'a> {
|
||||
stacked: &'a mut Stacked,
|
||||
ingredients: Vec<&'a Ingredient>,
|
||||
/// Indices into the stacked keys of the items any ingredient accepts.
|
||||
items: Vec<usize>,
|
||||
connection: Vec<bool>,
|
||||
assigned: Vec<bool>,
|
||||
satisfied: Vec<bool>,
|
||||
visited_ingredient: Vec<bool>,
|
||||
visited_item: Vec<bool>,
|
||||
path: Vec<usize>,
|
||||
}
|
||||
|
||||
impl<'a> Picker<'a> {
|
||||
fn new(stacked: &'a mut Stacked, ingredients: &[&'a Ingredient]) -> Self {
|
||||
// getUniqueAvailableIngredientItems
|
||||
let items: Vec<usize> = (0..stacked.keys.len())
|
||||
.filter(|&i| {
|
||||
stacked.amounts[i] > 0
|
||||
&& ingredients.iter().any(|g| g.0.contains(&*stacked.keys[i]))
|
||||
})
|
||||
.collect();
|
||||
let (ni, nt) = (ingredients.len(), items.len());
|
||||
let mut connection = vec![false; ni * nt];
|
||||
for (g, ing) in ingredients.iter().enumerate() {
|
||||
for (t, &key) in items.iter().enumerate() {
|
||||
if ing.0.contains(&*stacked.keys[key]) {
|
||||
connection[t * ni + g] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
stacked,
|
||||
ingredients: ingredients.to_vec(),
|
||||
items,
|
||||
connection,
|
||||
assigned: vec![false; ni * nt],
|
||||
satisfied: vec![false; ni],
|
||||
visited_ingredient: vec![false; ni],
|
||||
visited_item: vec![false; nt],
|
||||
path: Vec::new(),
|
||||
}
|
||||
}
|
||||
fn at(&self, item: usize, ingredient: usize) -> usize {
|
||||
item * self.ingredients.len() + ingredient
|
||||
}
|
||||
fn clear_visited(&mut self) {
|
||||
self.visited_ingredient.fill(false);
|
||||
self.visited_item.fill(false);
|
||||
}
|
||||
fn try_pick(&mut self, capacity: i32, mut output: Option<&mut Vec<Arc<str>>>) -> bool {
|
||||
if capacity <= 0 {
|
||||
return true;
|
||||
}
|
||||
let mut satisfied_count = 0;
|
||||
loop {
|
||||
let Some(path) = self.try_assigning_new_item(capacity) else {
|
||||
let valid = satisfied_count == self.ingredients.len();
|
||||
let has_output = valid && output.is_some();
|
||||
self.clear_visited();
|
||||
self.satisfied.fill(false);
|
||||
for g in 0..self.ingredients.len() {
|
||||
for t in 0..self.items.len() {
|
||||
let at = self.at(t, g);
|
||||
if self.assigned[at] {
|
||||
self.assigned[at] = false;
|
||||
let key = self.items[t];
|
||||
self.stacked.amounts[key] += capacity;
|
||||
if has_output && let Some(out) = output.as_deref_mut() {
|
||||
out.push(self.stacked.keys[key].clone());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
};
|
||||
let key = self.items[path[0]];
|
||||
self.stacked.amounts[key] -= capacity;
|
||||
self.satisfied[path[path.len() - 1]] = true;
|
||||
satisfied_count += 1;
|
||||
for i in 0..path.len() - 1 {
|
||||
if i & 1 == 0 {
|
||||
let at = self.at(path[i], path[i + 1]);
|
||||
self.assigned[at] = true;
|
||||
} else {
|
||||
let at = self.at(path[i + 1], path[i]);
|
||||
self.assigned[at] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn try_assigning_new_item(&mut self, capacity: i32) -> Option<Vec<usize>> {
|
||||
self.clear_visited();
|
||||
for t in 0..self.items.len() {
|
||||
if self.stacked.amounts[self.items[t]] >= capacity
|
||||
&& let Some(path) = self.find_path(t)
|
||||
{
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn find_path(&mut self, start: usize) -> Option<Vec<usize>> {
|
||||
self.path.clear();
|
||||
self.visited_item[start] = true;
|
||||
self.path.push(start);
|
||||
while !self.path.is_empty() {
|
||||
let len = self.path.len();
|
||||
if (len - 1) & 1 == 0 {
|
||||
let item = self.path[len - 1];
|
||||
for g in 0..self.ingredients.len() {
|
||||
let at = self.at(item, g);
|
||||
if !self.visited_ingredient[g] && self.connection[at] && !self.assigned[at] {
|
||||
self.visited_ingredient[g] = true;
|
||||
self.path.push(g);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let ingredient = self.path[len - 1];
|
||||
if !self.satisfied[ingredient] {
|
||||
return Some(self.path.clone());
|
||||
}
|
||||
for t in 0..self.items.len() {
|
||||
if !self.visited_item[t] && self.assigned[self.at(t, ingredient)] {
|
||||
self.visited_item[t] = true;
|
||||
self.path.push(t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.path.len() == len {
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn try_pick_all(&mut self, max_size: i32, output: Option<&mut Vec<Arc<str>>>) -> i32 {
|
||||
let mut min = 0i32;
|
||||
// Java int arithmetic: an empty ingredient list overflows as vanilla does.
|
||||
let mut max = max_size
|
||||
.min(self.stacked.upper_bound(&self.ingredients))
|
||||
.wrapping_add(1);
|
||||
loop {
|
||||
let mid = min.wrapping_add(max) / 2;
|
||||
if self.try_pick(mid, None) {
|
||||
if max.wrapping_sub(min) <= 1 {
|
||||
if mid > 0 {
|
||||
self.try_pick(mid, output);
|
||||
}
|
||||
return mid;
|
||||
}
|
||||
min = mid;
|
||||
} else {
|
||||
max = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeBookMenu.PostPlaceAction`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PostPlace {
|
||||
Nothing,
|
||||
/// The client shows the recipe as a ghost (`ClientboundPlaceGhostRecipePacket`).
|
||||
Ghost,
|
||||
}
|
||||
|
||||
/// The menu slots a placement works on.
|
||||
struct Grid {
|
||||
width: usize,
|
||||
height: usize,
|
||||
/// `inputGridSlots` and `slotsToClear` as menu slot indices.
|
||||
inputs: Vec<usize>,
|
||||
clear: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Menu {
|
||||
fn place_grid(&self) -> Option<Grid> {
|
||||
match self.kind {
|
||||
Kind::Inventory => Some(Grid {
|
||||
width: 2,
|
||||
height: 2,
|
||||
inputs: (1..5).collect(),
|
||||
clear: (1..5).collect(),
|
||||
}),
|
||||
Kind::Crafting => Some(Grid {
|
||||
width: 3,
|
||||
height: 3,
|
||||
inputs: (1..10).collect(),
|
||||
clear: (1..10).collect(),
|
||||
}),
|
||||
Kind::Furnace(_) => Some(Grid {
|
||||
width: 1,
|
||||
height: 1,
|
||||
inputs: vec![0],
|
||||
clear: vec![0, 2],
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Inventory.fillStackedContents` then the menu's
|
||||
/// `fillCraftSlotsStackedContents`.
|
||||
pub fn stacked_contents(&self, env: &Env) -> Stacked {
|
||||
let mut stacked = Stacked::default();
|
||||
for stack in self.containers[PLAYER][..36].iter().flatten() {
|
||||
stacked.account_simple(stack, Self::max_stack(env, stack));
|
||||
}
|
||||
match self.kind {
|
||||
// A furnace's SimpleContainer counts all three slots, unfiltered.
|
||||
Kind::Furnace(_) => {
|
||||
for stack in self.containers[MAIN].iter().flatten() {
|
||||
stacked.account_stack(stack, Self::max_stack(env, stack));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
for stack in self.containers[GRID].iter().flatten() {
|
||||
stacked.account_simple(stack, Self::max_stack(env, stack));
|
||||
}
|
||||
}
|
||||
}
|
||||
stacked
|
||||
}
|
||||
|
||||
/// `RecipeBookMenu.handlePlacement` for the recipe `id`
|
||||
/// (`ServerPlaceRecipe.placeRecipe`). `allow_drop` is the player being in
|
||||
/// creative; `order` the iteration order of the counted items, if known.
|
||||
pub fn place_recipe(
|
||||
&mut self,
|
||||
env: &Env,
|
||||
id: &str,
|
||||
use_max: bool,
|
||||
allow_drop: bool,
|
||||
order: Option<&[String]>,
|
||||
) -> PostPlace {
|
||||
let Some(grid) = self.place_grid() else {
|
||||
return PostPlace::Nothing;
|
||||
};
|
||||
let Some(placement) = env.recipes.placement(id) else {
|
||||
return PostPlace::Nothing;
|
||||
};
|
||||
if placement.impossible() {
|
||||
return PostPlace::Nothing;
|
||||
}
|
||||
if !allow_drop && !self.test_clear_grid(env, &grid) {
|
||||
return PostPlace::Nothing;
|
||||
}
|
||||
let mut stacked = self.stacked_contents(env);
|
||||
if let Some(order) = order {
|
||||
stacked.set_order(order);
|
||||
}
|
||||
let ingredients: Vec<&Ingredient> = placement.ingredients.iter().collect();
|
||||
let post = if stacked.try_pick(&ingredients, 1, None) {
|
||||
self.place(env, id, &grid, &placement, &mut stacked, use_max);
|
||||
PostPlace::Nothing
|
||||
} else {
|
||||
self.clear_grid(env, &grid);
|
||||
PostPlace::Ghost
|
||||
};
|
||||
// AbstractCraftingMenu.finishPlacingRecipe: the result follows the grid.
|
||||
self.recompute(env);
|
||||
post
|
||||
}
|
||||
|
||||
/// `recipeMatches`: the recipe already fills the grid.
|
||||
fn recipe_in_grid(&self, env: &Env, id: &str) -> bool {
|
||||
match self.kind {
|
||||
Kind::Furnace(_) => {
|
||||
let name = id.trim_start_matches("minecraft:");
|
||||
match (
|
||||
env.recipes.cooking.iter().find(|c| c.id == name),
|
||||
self.containers[MAIN][0].as_ref(),
|
||||
) {
|
||||
(Some(c), Some(input)) => c.ingredient.test(input),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
_ => env
|
||||
.recipes
|
||||
.recipe_matches(id, &self.containers[GRID], self.grid_size),
|
||||
}
|
||||
}
|
||||
|
||||
fn place(
|
||||
&mut self,
|
||||
env: &Env,
|
||||
id: &str,
|
||||
grid: &Grid,
|
||||
placement: &Placement,
|
||||
stacked: &mut Stacked,
|
||||
use_max: bool,
|
||||
) {
|
||||
let ingredients: Vec<&Ingredient> = placement.ingredients.iter().collect();
|
||||
let matches = self.recipe_in_grid(env, id);
|
||||
let biggest = stacked.try_pick_all(&ingredients, i32::MAX, None);
|
||||
if matches {
|
||||
for &s in &grid.inputs {
|
||||
if let Some(stack) = self.slot(s)
|
||||
&& (biggest.min(Self::max_stack(env, stack) as i32) as i64)
|
||||
< i64::from(stack.count) + 1
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// calculateAmountToCraft
|
||||
let amount = if use_max {
|
||||
biggest
|
||||
} else if matches {
|
||||
let smallest = grid
|
||||
.inputs
|
||||
.iter()
|
||||
.filter_map(|&s| self.slot(s))
|
||||
.map(|s| s.count as i32)
|
||||
.min();
|
||||
smallest.map_or(i32::MAX, |n| n + 1)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let mut used = Vec::new();
|
||||
if !stacked.try_pick(&ingredients, amount, Some(&mut used)) {
|
||||
return;
|
||||
}
|
||||
// clampToMaxStackSize
|
||||
let adjusted = used.iter().fold(amount, |n, item| {
|
||||
n.min(env.items.get(item).map_or(1, |i| i.max_stack) as i32)
|
||||
});
|
||||
if adjusted != amount {
|
||||
used.clear();
|
||||
if !stacked.try_pick(&ingredients, adjusted, Some(&mut used)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.clear_grid(env, grid);
|
||||
let (w, h) = placement.shaped.unwrap_or((grid.width, grid.height));
|
||||
let slots: Vec<i32> = placement.slots.clone();
|
||||
for (ingredient, index) in
|
||||
crate::recipe_book::place_cells(grid.width, grid.height, w, h, &slots)
|
||||
{
|
||||
if ingredient == -1 {
|
||||
continue;
|
||||
}
|
||||
let target = grid.inputs[index];
|
||||
let item = used[ingredient as usize].clone();
|
||||
let mut remaining = adjusted;
|
||||
while remaining > 0 {
|
||||
remaining = self.move_item_to_grid(target, &item, remaining);
|
||||
if remaining == -1 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `moveItemToGrid`: the rest still to move, or -1 when nothing matches.
|
||||
fn move_item_to_grid(&mut self, target: usize, item: &str, count: i32) -> i32 {
|
||||
let existing = self.slot(target).cloned();
|
||||
let found = (0..36).find(|&i| {
|
||||
self.containers[PLAYER][i].as_ref().is_some_and(|s| {
|
||||
&*s.item == item
|
||||
&& usable_for_crafting(s)
|
||||
&& existing
|
||||
.as_ref()
|
||||
.is_none_or(|e| e.same_item_same_components(s))
|
||||
})
|
||||
});
|
||||
let Some(i) = found else {
|
||||
return -1;
|
||||
};
|
||||
let cell = &mut self.containers[PLAYER][i];
|
||||
let taken = match cell.as_mut() {
|
||||
Some(have) if (count as u32) < have.count => split(have, count as u32),
|
||||
_ => cell.take().expect("found"),
|
||||
};
|
||||
tidy(cell);
|
||||
let taken_count = taken.count as i32;
|
||||
let slot = self.slots[target];
|
||||
match self.containers[slot.container][slot.index].as_mut() {
|
||||
None => self.containers[slot.container][slot.index] = Some(taken),
|
||||
Some(have) => have.count += taken.count,
|
||||
}
|
||||
count - taken_count
|
||||
}
|
||||
|
||||
/// `clearGrid`: the slots to clear go back to the inventory (or drop),
|
||||
/// then the grid empties (`clearCraftingContent`).
|
||||
fn clear_grid(&mut self, env: &Env, grid: &Grid) {
|
||||
for &s in &grid.clear {
|
||||
let slot = self.slots[s];
|
||||
if let Some(stack) = self.containers[slot.container][slot.index].clone() {
|
||||
let mut copy = stack;
|
||||
self.place_back(env, &mut copy);
|
||||
}
|
||||
}
|
||||
match self.kind {
|
||||
Kind::Furnace(_) => {
|
||||
for &s in &grid.clear {
|
||||
let slot = self.slots[s];
|
||||
self.containers[slot.container][slot.index] = None;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.containers[GRID].fill(None);
|
||||
self.containers[RESULT][0] = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Inventory.placeItemBackInInventory`.
|
||||
fn place_back(&mut self, env: &Env, stack: &mut ItemStack) {
|
||||
while stack.count > 0 {
|
||||
let slot = self
|
||||
.slot_with_space(env, stack)
|
||||
.or_else(|| (0..36).find(|&i| self.containers[PLAYER][i].is_none()));
|
||||
let Some(slot) = slot else {
|
||||
let dropped = std::mem::replace(
|
||||
stack,
|
||||
ItemStack {
|
||||
count: 0,
|
||||
..stack.clone()
|
||||
},
|
||||
);
|
||||
self.drop_stack(&dropped);
|
||||
break;
|
||||
};
|
||||
let have = self.containers[PLAYER][slot]
|
||||
.as_ref()
|
||||
.map_or(0, |s| s.count);
|
||||
let space = Self::max_stack(env, stack).saturating_sub(have);
|
||||
let mut part = split(stack, space);
|
||||
self.inventory_add_at(env, slot, &mut part);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Inventory.add(slot, stack)`.
|
||||
fn inventory_add_at(&mut self, env: &Env, slot: usize, stack: &mut ItemStack) {
|
||||
if stack.count == 0 {
|
||||
return;
|
||||
}
|
||||
if Self::damageable(env, stack) && stack.damage > 0 {
|
||||
self.containers[PLAYER][slot] = Some(stack.clone());
|
||||
stack.count = 0;
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
let last = stack.count;
|
||||
// addResource(slot, stack)
|
||||
let cell = self.containers[PLAYER][slot].get_or_insert_with(|| ItemStack {
|
||||
count: 0,
|
||||
..stack.clone()
|
||||
});
|
||||
let room = super::CONTAINER_MAX
|
||||
.min(Self::max_stack(env, cell))
|
||||
.saturating_sub(cell.count);
|
||||
let add = stack.count.min(room);
|
||||
cell.count += add;
|
||||
stack.count -= add;
|
||||
tidy(&mut self.containers[PLAYER][slot]);
|
||||
if stack.count == 0 || stack.count >= last {
|
||||
if stack.count == last && self.creative {
|
||||
stack.count = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `testClearGrid`: whether the inventory can take the grid back.
|
||||
fn test_clear_grid(&self, env: &Env, grid: &Grid) -> bool {
|
||||
let mut free_slots: Vec<ItemStack> = Vec::new();
|
||||
let free_in_inventory = self.containers[PLAYER][..36]
|
||||
.iter()
|
||||
.filter(|s| s.is_none())
|
||||
.count();
|
||||
for &s in &grid.inputs {
|
||||
let Some(mut stack) = self.slot(s).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let with_space = self.slot_with_space(env, &stack);
|
||||
if with_space.is_none() && free_slots.len() <= free_in_inventory {
|
||||
for listed in &mut free_slots {
|
||||
let max = Self::max_stack(env, listed);
|
||||
if listed.item == stack.item
|
||||
&& listed.count != max
|
||||
&& listed.count + stack.count <= max
|
||||
{
|
||||
listed.count += stack.count;
|
||||
stack.count = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if stack.count > 0 {
|
||||
if free_slots.len() >= free_in_inventory {
|
||||
return false;
|
||||
}
|
||||
free_slots.push(stack);
|
||||
}
|
||||
} else if with_space.is_none() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ing(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn have(items: &[(&str, i32)]) -> Stacked {
|
||||
let mut s = Stacked::default();
|
||||
for (item, n) in items {
|
||||
s.account(&Arc::from(*item), *n);
|
||||
}
|
||||
s
|
||||
}
|
||||
#[test]
|
||||
fn a_single_item_can_fill_several_ingredients() {
|
||||
let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]);
|
||||
let reqs = [&planks, &planks, &planks, &planks];
|
||||
let mut a = have(&[("minecraft:oak_planks", 2), ("minecraft:birch_planks", 2)]);
|
||||
assert!(a.can_craft(&reqs));
|
||||
// Two sets need 8 planks, but only 4 are there.
|
||||
assert!(!a.try_pick(&reqs, 2, None));
|
||||
assert_eq!(a.try_pick_all(&reqs, i32::MAX, None), 1);
|
||||
assert_eq!(
|
||||
have(&[("minecraft:oak_planks", 64)]).try_pick_all(&reqs, i32::MAX, None),
|
||||
16
|
||||
);
|
||||
// Picking leaves the counts as they were.
|
||||
assert!(a.try_pick(&reqs, 1, None));
|
||||
assert!(a.can_craft(&reqs));
|
||||
}
|
||||
#[test]
|
||||
fn the_matching_reassigns_flexible_ingredients() {
|
||||
// The first ingredient takes either item, the second only the stick:
|
||||
// the first item tried (the stick) moves over to free it.
|
||||
let any = ing(&["minecraft:stick", "minecraft:bone"]);
|
||||
let stick = ing(&["minecraft:stick"]);
|
||||
let mut a = have(&[("minecraft:stick", 1), ("minecraft:bone", 1)]);
|
||||
let mut used = Vec::new();
|
||||
assert!(a.try_pick(&[&any, &stick], 1, Some(&mut used)));
|
||||
assert_eq!(&*used[0], "minecraft:bone");
|
||||
assert_eq!(&*used[1], "minecraft:stick");
|
||||
assert!(!have(&[("minecraft:stick", 1)]).can_craft(&[&any, &stick]));
|
||||
}
|
||||
#[test]
|
||||
fn the_order_decides_between_fitting_items() {
|
||||
let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]);
|
||||
let mut a = have(&[("minecraft:oak_planks", 4), ("minecraft:birch_planks", 4)]);
|
||||
let mut used = Vec::new();
|
||||
a.try_pick(&[&planks], 1, Some(&mut used));
|
||||
assert_eq!(&*used[0], "minecraft:oak_planks");
|
||||
a.set_order(&["minecraft:birch_planks".to_owned()]);
|
||||
used.clear();
|
||||
a.try_pick(&[&planks], 1, Some(&mut used));
|
||||
assert_eq!(&*used[0], "minecraft:birch_planks");
|
||||
}
|
||||
#[test]
|
||||
fn damaged_or_named_stacks_are_not_counted() {
|
||||
let mut named = ItemStack::new("minecraft:stick", 4);
|
||||
named.data_mut().custom_name = Some("x".into());
|
||||
let mut damaged = ItemStack::new("minecraft:iron_sword", 1);
|
||||
damaged.damage = 3;
|
||||
let mut s = Stacked::default();
|
||||
for stack in [&named, &damaged, &ItemStack::new("minecraft:stick", 2)] {
|
||||
s.account_simple(stack, 64);
|
||||
}
|
||||
assert_eq!(s.keys().len(), 1);
|
||||
assert!(s.can_craft(&[&ing(&["minecraft:stick"]), &ing(&["minecraft:stick"])]));
|
||||
assert!(!s.can_craft(&[&ing(&["minecraft:stick"]); 3]));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
pub mod ai;
|
||||
pub mod allay;
|
||||
pub mod anim;
|
||||
pub mod animal_brain;
|
||||
pub mod aquatic;
|
||||
pub mod body_anim;
|
||||
pub mod brain;
|
||||
@@ -15,7 +16,9 @@ pub mod breeze;
|
||||
pub mod camel;
|
||||
pub mod caravan;
|
||||
pub mod control;
|
||||
pub mod copper_golem;
|
||||
pub mod creaking;
|
||||
pub mod creaking_heart;
|
||||
pub mod cube;
|
||||
pub mod data;
|
||||
pub mod drops;
|
||||
@@ -35,6 +38,7 @@ pub mod keyframes;
|
||||
pub mod leash;
|
||||
pub mod living;
|
||||
pub mod llama;
|
||||
pub mod monster_brain;
|
||||
pub mod nautilus;
|
||||
pub mod nav;
|
||||
pub mod nether;
|
||||
@@ -573,6 +577,8 @@ pub struct Extra {
|
||||
pub raider: Option<Box<raider::State>>,
|
||||
/// A villager's raid activity and gossip.
|
||||
pub villager: Option<Box<villager::Ext>>,
|
||||
/// The sniffer's and the ghastling's brain.
|
||||
pub animal_brain: Option<Box<animal_brain::Brain>>,
|
||||
/// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`).
|
||||
pub mount: Option<u32>,
|
||||
pub rider: Option<u32>,
|
||||
@@ -604,6 +610,8 @@ pub struct Extra {
|
||||
/// The school leader a fish follows, and a tropical fish that swims alone.
|
||||
pub leader: Option<u32>,
|
||||
pub lone: bool,
|
||||
/// A breeze's or creaking's brain (`monster_brain`).
|
||||
pub brain: Option<Box<monster_brain::Brain>>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Mob {
|
||||
@@ -677,8 +685,29 @@ pub struct Mob {
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum MobEvent {
|
||||
Sound(&'static str, [f64; 3], f32, f32),
|
||||
/// `OfferFlowerGoal.stop`: the item goes to the target's antenna (saddle)
|
||||
/// slot if it is empty, as a guaranteed drop.
|
||||
Gift {
|
||||
target: u32,
|
||||
item: &'static str,
|
||||
},
|
||||
/// `AnimalMakeLove`: the partner remembers this mob as its breed target
|
||||
/// and walks to it and looks at it.
|
||||
BreedTarget {
|
||||
mob: u32,
|
||||
partner: u32,
|
||||
},
|
||||
/// `BehaviorUtils.lockGazeAndWalkToEachOther`'s other half: the partner
|
||||
/// looks at this mob and walks to it.
|
||||
LockGaze {
|
||||
mob: u32,
|
||||
partner: u32,
|
||||
},
|
||||
/// A sound event id that is not a static string (variant sounds).
|
||||
SoundId(String, [f64; 3], f32, f32),
|
||||
/// `Level.playLocalSound`: a sound the client plays for itself, never
|
||||
/// sent by a server (a breeze's whirl and idle sounds).
|
||||
LocalSound(&'static str, [f64; 3], f32, f32),
|
||||
/// A level event's sound (`levelEvent`/`globalLevelEvent`): the client
|
||||
/// plays it with its own random pitch spread (`(a - b) * spread + 1`),
|
||||
/// nothing is drawn from the mob.
|
||||
@@ -775,6 +804,9 @@ pub enum MobEvent {
|
||||
Breed {
|
||||
parent: u32,
|
||||
partner: u32,
|
||||
/// A llama's baby, drawn from the parent's random as
|
||||
/// `Llama.getBreedOffspring` does.
|
||||
llama: Option<Box<super::mobs::llama::Offspring>>,
|
||||
},
|
||||
/// Replace a block by name (sheep turning grass to dirt), optionally with
|
||||
/// the destroy effect.
|
||||
@@ -949,9 +981,13 @@ pub struct Seen {
|
||||
/// A villager's `POTENTIAL_JOB_SITE` and `MEETING_POINT`.
|
||||
pub potential_job: Option<[i32; 3]>,
|
||||
pub meeting: Option<[i32; 3]>,
|
||||
/// A villager's profession (index into `render::PROFESSIONS`) and experience.
|
||||
/// `variant2`: a villager's profession (index into
|
||||
/// `render::PROFESSIONS`), a llama's strength. And a villager's experience.
|
||||
pub profession: u8,
|
||||
pub xp: i32,
|
||||
/// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a
|
||||
/// horse's breeding stock).
|
||||
pub stats: [f64; 3],
|
||||
}
|
||||
impl Mob {
|
||||
/// `EntityType.getCategory`'s name.
|
||||
@@ -997,6 +1033,41 @@ pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) {
|
||||
false
|
||||
});
|
||||
}
|
||||
/// Applies the brain memories a mob's tick set on other mobs (from event
|
||||
/// index `from` on), at once: vanilla sets them on the other entity during
|
||||
/// the tick, before the mobs after it tick.
|
||||
pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec<MobEvent>, from: usize) {
|
||||
let mut i = from;
|
||||
while i < events.len() {
|
||||
match events[i] {
|
||||
MobEvent::BreedTarget { mob, partner } => {
|
||||
if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) {
|
||||
animal_brain::set_breed_partner(m, partner);
|
||||
}
|
||||
events.remove(i);
|
||||
}
|
||||
MobEvent::LockGaze { mob, partner } => {
|
||||
if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) {
|
||||
animal_brain::lock_gaze(m, partner);
|
||||
}
|
||||
events.remove(i);
|
||||
}
|
||||
// Animal.finalizeSpawnChildFromBreeding: the partner rests and
|
||||
// forgets it at once (the game still makes the baby).
|
||||
MobEvent::Breed {
|
||||
parent, partner, ..
|
||||
} => {
|
||||
if let Some(m) = mobs.iter_mut().find(|m| m.id == partner) {
|
||||
m.extra.age = 6000;
|
||||
m.extra.in_love = 0;
|
||||
animal_brain::forget_breed_target(m, parent);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The player as mobs see it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PlayerView {
|
||||
@@ -1024,6 +1095,9 @@ pub struct PlayerView {
|
||||
pub hero: bool,
|
||||
/// The player's UUID (villagers' gossip is keyed by it).
|
||||
pub uuid: [i32; 4],
|
||||
/// The mobs on the player's team (`isAlliedTo`): combat targeting
|
||||
/// leaves the player alone.
|
||||
pub allies: std::sync::Arc<std::collections::HashSet<u32>>,
|
||||
}
|
||||
pub struct MobWorld<'a> {
|
||||
pub world: &'a World,
|
||||
@@ -1051,6 +1125,22 @@ pub struct MobWorld<'a> {
|
||||
pub world_seed: i64,
|
||||
/// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world).
|
||||
pub sea_level: i32,
|
||||
/// The scoreboard teams of the player and the mobs (collision rules).
|
||||
pub teams: Teams,
|
||||
}
|
||||
/// `Entity.getTeam` of the player and of the mobs on a team.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Teams {
|
||||
pub player: Option<crate::scoreboard::Team>,
|
||||
pub mobs: HashMap<u32, crate::scoreboard::Team>,
|
||||
}
|
||||
impl Teams {
|
||||
pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> {
|
||||
match who {
|
||||
Who::Player => self.player.as_ref(),
|
||||
Who::Mob(id) => self.mobs.get(&id),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Mob {
|
||||
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
|
||||
@@ -1192,6 +1282,7 @@ impl Mob {
|
||||
.fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
|
||||
}
|
||||
pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
|
||||
raider::note_hurt(self);
|
||||
if !self.alive() || self.removed || self.invulnerable_flag {
|
||||
return false;
|
||||
}
|
||||
@@ -1445,8 +1536,10 @@ impl Mob {
|
||||
/// Wear (or take off) a saddle stack, keeping its components.
|
||||
pub fn set_saddle(&mut self, saddle: Option<crate::items::ItemStack>) {
|
||||
self.extra.saddled = saddle.is_some();
|
||||
// A plain saddle is implied by `saddled`; anything else (a copper
|
||||
// golem's antenna flower) is kept as it is.
|
||||
self.extra.saddle_stack = saddle
|
||||
.map(|s| crate::items::ItemStack { count: 1, ..s })
|
||||
.filter(|s| s.damage != 0 || s.extra.is_some());
|
||||
.filter(|s| s.damage != 0 || s.extra.is_some() || &*s.item != "minecraft:saddle");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ use horizon_core::{
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ai {
|
||||
/// `Mob.homePosition` and `homeRadius`: where a restricted mob stays
|
||||
/// (a lead's holder, a happy ghast's float area).
|
||||
pub home: Option<([i32; 3], i32)>,
|
||||
pub goals: GoalSelector,
|
||||
pub targets: GoalSelector,
|
||||
pub nav: Navigation,
|
||||
@@ -128,7 +131,7 @@ pub fn family(s: Species) -> Family {
|
||||
S::Witch => Family::Witch,
|
||||
S::Wolf | S::Cat => Family::Tame,
|
||||
S::Blaze | S::Ghast => Family::Nether,
|
||||
S::IronGolem | S::SnowGolem => Family::Golem,
|
||||
S::IronGolem | S::SnowGolem | S::CopperGolem => Family::Golem,
|
||||
S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => Family::Illager,
|
||||
S::Vex => Family::Vex,
|
||||
S::Ravager => Family::Ravager,
|
||||
@@ -176,6 +179,7 @@ pub fn register(m: &mut Mob) {
|
||||
Family::Nether if m.species() == Species::Ghast => super::nether::register_ghast(m),
|
||||
Family::Nether => super::nether::register_blaze(m),
|
||||
Family::Golem if m.species() == Species::IronGolem => super::golem::register_iron(m),
|
||||
Family::Golem if m.species() == Species::CopperGolem => super::copper_golem::register(m),
|
||||
Family::Golem => super::golem::register_snow(m),
|
||||
Family::Illager if m.species() == Species::Pillager => super::illager::register_pillager(m),
|
||||
Family::Illager if m.species() == Species::Evoker => super::illager::register_evoker(m),
|
||||
@@ -212,6 +216,9 @@ fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if m.species() == Species::Wither && m.alive() {
|
||||
super::wither::steer(m);
|
||||
}
|
||||
if m.species() == Species::Breeze {
|
||||
super::breeze::tick(m, events);
|
||||
}
|
||||
match family(m.species()) {
|
||||
Family::Hostile => {
|
||||
if m.species() == Species::Creeper {
|
||||
@@ -354,8 +361,9 @@ pub fn tick(
|
||||
if !m.no_ai {
|
||||
ai_step(m, w, level_random, events);
|
||||
}
|
||||
// Mob.tickHeadTurn -> BodyRotationControl.clientTick
|
||||
if m.alive() {
|
||||
// Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen
|
||||
// creaking's waits).
|
||||
if m.alive() && !(super::creaking::is_creaking(m) && !super::creaking::can_move(m)) {
|
||||
m.body_rotation_tick();
|
||||
}
|
||||
events.append(&mut m.outbox);
|
||||
@@ -527,11 +535,14 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
},
|
||||
// Breeze.playAmbientSound.
|
||||
Species::Breeze => match super::breeze::ambient(m) {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
},
|
||||
// Breeze.playAmbientSound: a local sound, nothing drawn.
|
||||
Species::Breeze => {
|
||||
if let Some(s) = super::breeze::ambient(m) {
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
events.push(MobEvent::LocalSound(s, at, 1.0, 1.0));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Creaking.getAmbientSound: silent while awake.
|
||||
Species::Creaking if m.extra.flag => return,
|
||||
// Shulker.playAmbientSound: silent while closed.
|
||||
@@ -555,6 +566,10 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
.is_some_and(|t| t.position.distance_squared(m.position) > 121.0);
|
||||
super::witch::ai_step(m, events, far);
|
||||
}
|
||||
// AbstractHorse.aiStep: the tail swishes now and then (moveTail).
|
||||
if super::equine::is_equine(m.species()) {
|
||||
let _ = m.random.next_int_bound(200);
|
||||
}
|
||||
// Monster.aiStep: updateNoActionTime (Raider: always +2).
|
||||
if is_monster(m.species())
|
||||
&& (super::raider::is_raider(m.species()) || super::hostile::mob_brightness(m, w) > 0.5)
|
||||
@@ -600,7 +615,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
// AgeableMob.aiStep
|
||||
if m.alive() {
|
||||
if m.extra.age < 0 {
|
||||
let (bw, bh, _) = m.dims();
|
||||
m.extra.age += 1;
|
||||
// setAge at the age boundary: refreshDimensions.
|
||||
if m.extra.age >= 0 {
|
||||
m.fudge_position_after_size_change(w, bw, bh);
|
||||
}
|
||||
} else if m.extra.age > 0 {
|
||||
m.extra.age -= 1;
|
||||
}
|
||||
@@ -611,13 +631,18 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
if m.extra.in_love > 0 {
|
||||
m.extra.in_love -= 1;
|
||||
if m.extra.in_love % 10 == 0 {
|
||||
// The heart's speed and getRandomX/Y/Z, drawn even on the server.
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
let r = &mut m.random;
|
||||
for _ in 0..3 {
|
||||
let _ = r.next_gaussian();
|
||||
}
|
||||
let x = m.position.x + w * (2.0 * r.next_double() - 1.0);
|
||||
let y = m.position.y + h * r.next_double() + 0.5;
|
||||
let z = m.position.z + w * (2.0 * r.next_double() - 1.0);
|
||||
events.push(MobEvent::Particles {
|
||||
kind: "heart",
|
||||
at: [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) + 0.5,
|
||||
m.position.z,
|
||||
],
|
||||
at: [x, y, z],
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
@@ -677,6 +702,9 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
targets.push((Who::Mob(o.id), o.position));
|
||||
}
|
||||
}
|
||||
// EntitySelector.pushableBy(this): the teams' collision rules.
|
||||
let own = w.teams.of(Who::Mob(m.id));
|
||||
targets.retain(|(who, _)| crate::scoreboard::pushable_by(own, w.teams.of(*who), true));
|
||||
// Cramming (maxEntityCramming 24).
|
||||
if targets.len() > 23 {
|
||||
let _ = m.random.next_int_bound(4);
|
||||
@@ -726,9 +754,9 @@ fn server_ai_step(
|
||||
events: &mut Vec<MobEvent>,
|
||||
) {
|
||||
m.ai.no_action_time += 1;
|
||||
// A creaking looked at stands still.
|
||||
if super::creaking::is_creaking(m) && !super::creaking::can_move(m) {
|
||||
return;
|
||||
// A happy ghast set up for its age (ageBoundaryReached runs at once).
|
||||
if m.species() == Species::HappyGhast {
|
||||
super::happy_ghast::ensure_setup(m);
|
||||
}
|
||||
// A saddled mount follows its rider instead of its goals.
|
||||
if super::equine::controlled(m) {
|
||||
@@ -752,16 +780,34 @@ fn server_ai_step(
|
||||
}
|
||||
m.ai.targets = targets;
|
||||
m.ai.goals = goals;
|
||||
m.nav_tick(w);
|
||||
// A creaking looked at stands still: its navigation, move, look and jump
|
||||
// controls wait (CreakingPathNavigation and the Creaking*Control).
|
||||
let frozen = super::creaking::is_creaking(m) && !super::creaking::can_move(m);
|
||||
if !frozen {
|
||||
m.nav_tick(w);
|
||||
}
|
||||
if super::monster_brain::has_brain(m.species()) {
|
||||
// Breeze/Creaking.customServerAiStep: the brain, then updateActivity.
|
||||
super::monster_brain::tick(m, w, level_random, events);
|
||||
}
|
||||
if m.species() == Species::Villager {
|
||||
// Villager.customServerAiStep: the brain, then the raid sound roll.
|
||||
super::villager_brain::tick(m, w, level_random, events);
|
||||
let _ = m.random.next_int_bound(100);
|
||||
}
|
||||
// Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's
|
||||
// only while it is a ghastling), then updateActivity.
|
||||
if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() {
|
||||
super::animal_brain::tick(m, w, level_random, events);
|
||||
}
|
||||
{
|
||||
let mut cx = Cx { w, events };
|
||||
custom_server_ai_step(m, &mut cx);
|
||||
}
|
||||
if frozen {
|
||||
m.ai.jumping = false;
|
||||
return;
|
||||
}
|
||||
m.move_control_tick(w, events);
|
||||
m.look_control_tick();
|
||||
m.jump_control_tick();
|
||||
@@ -811,7 +857,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
Species::Ravager => super::ravager::ai_step(m, w, events),
|
||||
Species::Wither => super::wither::ai_step(m, w, events),
|
||||
Species::Allay => super::allay::ai_step(m),
|
||||
Species::Breeze => super::breeze::ai_step(m, events),
|
||||
Species::Breeze => super::breeze::ai_step(m),
|
||||
Species::Sniffer => super::sniffer::ai_step(m, events),
|
||||
Species::HappyGhast => super::happy_ghast::ai_step(m, w),
|
||||
Species::Villager => super::villager::ai_step(m, w),
|
||||
@@ -824,6 +870,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
super::shulker::ai_step(m, w, events);
|
||||
}
|
||||
Species::SnowGolem => super::golem::snow_ai_step(m, w, events),
|
||||
Species::CopperGolem => super::copper_golem::ai_step(m, w, events),
|
||||
Species::Slime | Species::MagmaCube => super::cube::ai_step(m, w, events),
|
||||
Species::SulfurCube => {
|
||||
super::cube::ai_step(m, w, events);
|
||||
@@ -930,8 +977,22 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
if family(m.species()) == Family::Guardian && w.fluid(p[0], p[1], p[2]) == Fluid::Water {
|
||||
return 10.0 + light();
|
||||
}
|
||||
// AbstractNautilus.getWalkTargetValue: everywhere alike.
|
||||
if matches!(m.species(), Species::Nautilus | Species::ZombieNautilus) {
|
||||
// HappyGhast.getWalkTargetValue: open air, best just above the ground.
|
||||
if m.species() == Species::HappyGhast {
|
||||
let air = |y: i32| w.facts.is_air(w.world.block(p[0], y, p[2]));
|
||||
return if !air(p[1]) {
|
||||
0.0
|
||||
} else if air(p[1] - 1) && !air(p[1] - 2) {
|
||||
10.0
|
||||
} else {
|
||||
5.0
|
||||
};
|
||||
}
|
||||
// AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike.
|
||||
if matches!(
|
||||
m.species(),
|
||||
Species::Nautilus | Species::ZombieNautilus | Species::Creaking
|
||||
) {
|
||||
return 0.0;
|
||||
}
|
||||
if m.hostile()
|
||||
@@ -1077,6 +1138,10 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
|
||||
source,
|
||||
}),
|
||||
}
|
||||
// Mob.doHurtTarget ends with playAttackSound once the hit landed.
|
||||
if super::creaking::is_creaking(m) {
|
||||
m.voice("entity.creaking.attack", cx.events);
|
||||
}
|
||||
let _ = Fluid::None;
|
||||
}
|
||||
/// Mob.ate (sheep regrow wool, babies grow).
|
||||
|
||||
@@ -39,6 +39,7 @@ pub enum Anim {
|
||||
Villager,
|
||||
IronGolem,
|
||||
SnowGolem,
|
||||
CopperGolem,
|
||||
Illager,
|
||||
Piglin,
|
||||
ZombifiedPiglin,
|
||||
@@ -462,9 +463,11 @@ pub fn setup(
|
||||
Anim::Camel => super::camel::anim(m, s, p, w_anims),
|
||||
Anim::Breeze => super::breeze::anim(m, s, p, w_anims),
|
||||
Anim::Sniffer => super::sniffer::anim(m, s, p, w_anims),
|
||||
Anim::CopperGolem => super::copper_golem::anim(m, s, p, w_anims),
|
||||
Anim::HappyGhast => super::happy_ghast::anim(m, s, p),
|
||||
Anim::Nautilus => super::nautilus::anim(m, s, p, w_anims),
|
||||
Anim::Llama => super::llama::anim(m, s, p),
|
||||
// body_anim::llama runs first.
|
||||
Anim::Llama => quadruped(p, s),
|
||||
Anim::Warden => super::warden::anim(m, s, p, w_anims),
|
||||
Anim::Allay => super::allay::anim(m, s, p),
|
||||
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,474 +1,43 @@
|
||||
//! Breezes (`Breeze`, `BreezeAi`): the brain's idle and fight activities as
|
||||
//! one simulation (start attacking the nearest player or iron golem or whoever
|
||||
//! hurt it, slide to a walk target, then shoot, long jump, shoot when stuck or
|
||||
//! slide), memories with vanilla's expiry, the poses and their animations,
|
||||
//! `BreezeModel`'s layers and the wind charges it shoots.
|
||||
//! Breezes (`Breeze`): the poses and their animations, the long jump's
|
||||
//! arithmetic, the sounds of `Breeze.tick` and `BreezeModel`'s layers. The
|
||||
//! brain (`BreezeAi` and its behaviours) is in `monster_brain`.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
anim::{Poses, State},
|
||||
goals::{Cx, Float, Goal, goal_clone},
|
||||
keyframes::Animation,
|
||||
};
|
||||
use crate::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::collections::HashMap;
|
||||
|
||||
// Breeze state (see `brain`): `variant3` the pose, `variant` the pose the
|
||||
// animations last saw, `ints[0..6]` the memories (shoot, shoot cooldown,
|
||||
// shoot charging, shoot recovering, jump cooldown, jump inhaling) as the
|
||||
// remaining ticks plus one, `point` the walk target with `vector[0]` its
|
||||
// speed and `vector[1]` how close is close enough, `home` the jump target,
|
||||
// `vector[2]` the whirl sound clock, `flag` the long jump behaviour with its
|
||||
// end tick in `anim_ticks`, `flag2` the shoot behaviour with its end tick in
|
||||
// `egg_time`, `counter` the end tick of the slide to the walk target (0 when
|
||||
// not sliding), `counter2` the end tick of doing nothing, `anger` the
|
||||
// cooldown before the next try to walk, `scratch[0]` the ticks it may still
|
||||
// be unable to attack its target. AnimState states:
|
||||
// idle, shoot, slide, slide back, inhale, long jump.
|
||||
// `variant3` is the pose, `variant` the pose the animations last saw,
|
||||
// `vector[2]` `soundTick`. AnimState states: idle, shoot, slide, slide back,
|
||||
// inhale, long jump.
|
||||
pub const STANDING: u8 = 0;
|
||||
pub const SHOOTING: u8 = 1;
|
||||
pub const INHALING: u8 = 2;
|
||||
pub const LONG_JUMPING: u8 = 3;
|
||||
pub const SLIDING: u8 = 4;
|
||||
|
||||
const SHOOT: usize = 0;
|
||||
const SHOOT_COOLDOWN: usize = 1;
|
||||
const SHOOT_CHARGING: usize = 2;
|
||||
const SHOOT_RECOVERING: usize = 3;
|
||||
const JUMP_COOLDOWN: usize = 4;
|
||||
const JUMP_INHALING: usize = 5;
|
||||
|
||||
const SHOOT_INITIAL_DELAY: i32 = 15;
|
||||
const SHOOT_RECOVER_DELAY: i32 = 4;
|
||||
const SHOOT_COOLDOWN_TICKS: i32 = 10;
|
||||
const INHALING_TICKS: i32 = 10;
|
||||
const ALLOWED_ANGLES: [i32; 5] = [40, 55, 60, 75, 80];
|
||||
|
||||
/// `Breeze`'s constructor: no goals, the brain thinks (`monster_brain`).
|
||||
pub fn register(m: &mut Mob) {
|
||||
m.set_malus(super::path::PathType::OnTopOfTrapdoor, -1.0);
|
||||
m.set_malus(super::path::PathType::Fire, -1.0);
|
||||
// Swim(0.8) and the brain.
|
||||
m.ai.goals.add(0, Float);
|
||||
m.ai.goals.add(0, Brain);
|
||||
}
|
||||
pub fn pose(m: &Mob) -> u8 {
|
||||
m.extra.variant3
|
||||
}
|
||||
fn set_pose(m: &mut Mob, pose: u8) {
|
||||
pub(super) fn set_pose(m: &mut Mob, pose: u8) {
|
||||
m.extra.variant3 = pose;
|
||||
}
|
||||
fn has(m: &Mob, memory: usize) -> bool {
|
||||
m.extra.ints[memory] > 0
|
||||
}
|
||||
/// `Brain.setMemoryWithExpiry`: present now and for `ttl` more ticks.
|
||||
fn remember(m: &mut Mob, memory: usize, ttl: i32) {
|
||||
m.extra.ints[memory] = ttl + 1;
|
||||
}
|
||||
fn forget(m: &mut Mob, memory: usize) {
|
||||
m.extra.ints[memory] = 0;
|
||||
}
|
||||
fn walk_target(m: &Mob) -> bool {
|
||||
m.extra.point.is_some()
|
||||
}
|
||||
fn now(m: &Mob) -> i32 {
|
||||
m.age as i32
|
||||
}
|
||||
/// `Breeze.getFiringYPosition`.
|
||||
pub fn firing_y(m: &Mob) -> f64 {
|
||||
m.position.y + f64::from(m.height()) / 2.0 + f64::from(0.3_f32)
|
||||
}
|
||||
/// `Breeze.withinInnerCircleRange`.
|
||||
fn within_inner_circle(m: &Mob, target: Vec3) -> bool {
|
||||
let me = Vec3::new(
|
||||
m.position.x.floor() + 0.5,
|
||||
m.position.y.floor() + 0.5,
|
||||
m.position.z.floor() + 0.5,
|
||||
);
|
||||
(target.x - me.x).powi(2) + (target.z - me.z).powi(2) < 16.0 && (target.y - me.y).abs() < 10.0
|
||||
}
|
||||
/// `Entity.lookAt` with the eyes anchor: snap body and head to face a point.
|
||||
fn snap_look(m: &mut Mob, at: [f64; 3]) {
|
||||
let (dx, dy, dz) = (
|
||||
at[0] - m.position.x,
|
||||
at[1] - m.eye_y(),
|
||||
at[2] - m.position.z,
|
||||
);
|
||||
let flat = (dx * dx + dz * dz).sqrt();
|
||||
m.head_pitch = (-dy.atan2(flat).to_degrees()) as f32;
|
||||
m.yaw = (dz.atan2(dx).to_degrees() - 90.0) as f32;
|
||||
m.head_yaw = m.yaw;
|
||||
m.previous_head_pitch = m.head_pitch;
|
||||
m.previous_yaw = m.yaw;
|
||||
m.previous_head_yaw = m.yaw;
|
||||
}
|
||||
/// `BreezeUtil.hasLineOfSight`.
|
||||
fn line_of_sight(m: &Mob, w: &MobWorld, target: Vec3) -> bool {
|
||||
let from = m.position;
|
||||
let range = 50.0_f64.max(m.attrs.follow_range);
|
||||
from.distance(target) <= range && w.clear_between(from, target, false)
|
||||
}
|
||||
/// `BreezeUtil.randomPointBehindTarget`: four to eight blocks behind the
|
||||
/// target's facing, with a spread of 45 degrees.
|
||||
fn point_behind(m: &mut Mob, target: Vec3, head_yaw: f32) -> Vec3 {
|
||||
let view = head_yaw + 180.0 + m.random.next_gaussian() as f32 * 90.0 / 2.0;
|
||||
let r = 4.0 + m.random.next_float() * 4.0;
|
||||
let d = Vec3::direction_from_rotation(0.0, view).scale(f64::from(r));
|
||||
target.add_vector(d)
|
||||
}
|
||||
/// The attack target's position, eye height, facing and whether it is a
|
||||
/// player.
|
||||
struct Quarry {
|
||||
position: Vec3,
|
||||
eye: f64,
|
||||
yaw: f32,
|
||||
height: f64,
|
||||
}
|
||||
fn quarry(m: &Mob, cx: &Cx, who: Who) -> Option<Quarry> {
|
||||
let t = cx.w.target_info(who)?;
|
||||
let yaw = match who {
|
||||
Who::Player => {
|
||||
cx.w.player
|
||||
.as_ref()
|
||||
.map_or(0.0, |p| (-p.look[0]).atan2(p.look[2]).to_degrees() as f32)
|
||||
}
|
||||
Who::Mob(id) => cx.w.seen(id).map_or(m.yaw, |s| s.yaw),
|
||||
};
|
||||
Some(Quarry {
|
||||
position: t.position,
|
||||
eye: t.eye_y,
|
||||
yaw,
|
||||
height: t.bounds.max_position().y - t.bounds.min_position().y,
|
||||
})
|
||||
}
|
||||
/// `TargetingConditions.forCombat().range(follow)` plus `canAttack`: a
|
||||
/// player (not in creative or spectator) or an iron golem it can see.
|
||||
fn attackable(m: &mut Mob, cx: &Cx, who: Who) -> bool {
|
||||
let follow = m.attrs.follow_range;
|
||||
match who {
|
||||
Who::Player => m.can_target_player(cx.w, follow, true),
|
||||
Who::Mob(id) => {
|
||||
let Some(s) = cx.w.seen(id) else {
|
||||
return false;
|
||||
};
|
||||
s.alive
|
||||
&& s.species == Species::IronGolem
|
||||
&& m.distance_sqr(s.position) <= follow * follow
|
||||
&& m.sees(cx.w, who)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `BreezeAttackEntitySensor` and `HurtBySensor`: candidates for
|
||||
/// `StartAttacking`.
|
||||
fn nearest_attackable(m: &mut Mob, cx: &Cx) -> Option<Who> {
|
||||
let follow = m.attrs.follow_range;
|
||||
let mut candidates: Vec<(f64, Who)> = Vec::new();
|
||||
if let Some(p) = &cx.w.player
|
||||
&& p.alive
|
||||
&& !p.creative
|
||||
&& !p.spectator
|
||||
{
|
||||
candidates.push((m.distance_sqr(p.position), Who::Player));
|
||||
}
|
||||
for s in
|
||||
cx.w.nearby(m.position, follow, |s| s.species == Species::IronGolem)
|
||||
{
|
||||
candidates.push((m.distance_sqr(s.position), Who::Mob(s.id)));
|
||||
}
|
||||
candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
candidates
|
||||
.into_iter()
|
||||
.map(|c| c.1)
|
||||
.find(|w| attackable(m, cx, *w))
|
||||
}
|
||||
fn hurt_by(m: &Mob, cx: &Cx) -> Option<Who> {
|
||||
let (d, at) = m.last_damage?;
|
||||
if i64::from(m.age) - at > 40 {
|
||||
return None;
|
||||
}
|
||||
match d.attacker? {
|
||||
Who::Player => Some(Who::Player),
|
||||
Who::Mob(id) => {
|
||||
cx.w.seen(id)
|
||||
.filter(|s| s.alive && s.species == Species::IronGolem)
|
||||
.map(|_| Who::Mob(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The goal that runs the brain every tick.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Brain;
|
||||
impl Goal for Brain {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
true
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
brain(m, cx);
|
||||
}
|
||||
}
|
||||
/// `Brain.tick`: memories expire, sensors scan, behaviours start in
|
||||
/// priority order for the active activity, then the running ones tick.
|
||||
fn brain(m: &mut Mob, cx: &mut Cx) {
|
||||
for i in 0..6 {
|
||||
if m.extra.ints[i] > 0 {
|
||||
m.extra.ints[i] -= 1;
|
||||
}
|
||||
}
|
||||
if m.extra.anger > 0 {
|
||||
m.extra.anger -= 1;
|
||||
}
|
||||
let fight = m.ai.target.is_some() && !walk_target(m);
|
||||
if fight {
|
||||
stop_if_target_invalid(m, cx);
|
||||
start_shoot(m, cx);
|
||||
start_long_jump(m, cx);
|
||||
start_shoot_when_stuck(m);
|
||||
start_slide(m, cx);
|
||||
} else {
|
||||
// StartAttacking on the nearest attackable, then on whoever hurt it.
|
||||
if m.ai.target.is_none() {
|
||||
let scan = (m.age + m.id).is_multiple_of(20);
|
||||
let found = if scan {
|
||||
nearest_attackable(m, cx)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let found = found.or_else(|| hurt_by(m, cx));
|
||||
if let Some(who) = found {
|
||||
m.ai.target = Some(who);
|
||||
m.extra.anger = 0;
|
||||
m.extra.counter2 = 0;
|
||||
}
|
||||
}
|
||||
start_walking(m, cx);
|
||||
idle_stroll(m, cx);
|
||||
}
|
||||
tick_shoot(m, cx);
|
||||
tick_long_jump(m, cx);
|
||||
tick_walking(m, cx);
|
||||
}
|
||||
/// `StopAttackingIfTargetInvalid` with `wasEntityAttackableLastNTicks(100)`:
|
||||
/// the target is dropped once it has not been attackable for 100 ticks.
|
||||
fn stop_if_target_invalid(m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(who) = m.ai.target else { return };
|
||||
let alive = cx.w.target_info(who).is_some_and(|t| t.alive);
|
||||
if alive && attackable(m, cx, who) {
|
||||
m.extra.scratch[0] = 100;
|
||||
return;
|
||||
}
|
||||
m.extra.scratch[0] -= 1;
|
||||
if !alive || m.extra.scratch[0] < 0 {
|
||||
m.ai.target = None;
|
||||
m.extra.scratch[0] = 0;
|
||||
}
|
||||
}
|
||||
/// `Shoot.checkExtraStartConditions` and `start`.
|
||||
fn start_shoot(m: &mut Mob, cx: &mut Cx) {
|
||||
if m.extra.flag2
|
||||
|| !has(m, SHOOT)
|
||||
|| has(m, SHOOT_COOLDOWN)
|
||||
|| has(m, SHOOT_CHARGING)
|
||||
|| has(m, SHOOT_RECOVERING)
|
||||
|| walk_target(m)
|
||||
|| m.extra.home.is_some()
|
||||
|| pose(m) != STANDING
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else {
|
||||
return;
|
||||
};
|
||||
if m.position.distance_squared(q.position) >= 256.0 {
|
||||
forget(m, SHOOT);
|
||||
return;
|
||||
}
|
||||
m.extra.flag2 = true;
|
||||
m.extra.egg_time = now(m) + SHOOT_INITIAL_DELAY + 1 + SHOOT_RECOVER_DELAY;
|
||||
set_pose(m, SHOOTING);
|
||||
remember(m, SHOOT_CHARGING, SHOOT_INITIAL_DELAY);
|
||||
let at = m.center();
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.inhale", at, 1.0, 1.0));
|
||||
}
|
||||
fn tick_shoot(m: &mut Mob, cx: &mut Cx) {
|
||||
if !m.extra.flag2 {
|
||||
return;
|
||||
}
|
||||
let target = m.ai.target;
|
||||
if now(m) > m.extra.egg_time || target.is_none() || !has(m, SHOOT) {
|
||||
// Shoot.stop.
|
||||
m.extra.flag2 = false;
|
||||
if pose(m) == SHOOTING {
|
||||
set_pose(m, STANDING);
|
||||
}
|
||||
remember(m, SHOOT_COOLDOWN, SHOOT_COOLDOWN_TICKS);
|
||||
forget(m, SHOOT);
|
||||
return;
|
||||
}
|
||||
let Some(q) = target.and_then(|w| quarry(m, cx, w)) else {
|
||||
return;
|
||||
};
|
||||
snap_look(m, [q.position.x, q.eye, q.position.z]);
|
||||
if !has(m, SHOOT_CHARGING) && !has(m, SHOOT_RECOVERING) {
|
||||
remember(m, SHOOT_RECOVERING, SHOOT_RECOVER_DELAY);
|
||||
let start = Vec3::new(m.position.x, firing_y(m), m.position.z);
|
||||
let passenger_offset = 0.3;
|
||||
let (xd, yd, zd) = (
|
||||
q.position.x - m.position.x,
|
||||
q.position.y + q.height * passenger_offset - start.y,
|
||||
q.position.z - m.position.z,
|
||||
);
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::BreezeWindCharge,
|
||||
start,
|
||||
Some(Who::Mob(m.id)),
|
||||
);
|
||||
// 5 - 4 * difficulty at normal.
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd, zd],
|
||||
0.7,
|
||||
-3.0,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.shoot", m.center(), 1.5, 1.0));
|
||||
}
|
||||
}
|
||||
/// `ShootWhenStuck`.
|
||||
fn start_shoot_when_stuck(m: &mut Mob) {
|
||||
if has(m, SHOOT) || has(m, JUMP_INHALING) || m.extra.home.is_some() || walk_target(m) {
|
||||
return;
|
||||
}
|
||||
if m.rider.is_some() || m.fluids.in_water || m.extra.levitation_effect() {
|
||||
remember(m, SHOOT, 60);
|
||||
}
|
||||
}
|
||||
impl super::Extra {
|
||||
fn levitation_effect(&self) -> bool {
|
||||
self.effects.iter().any(|e| e.0 == "minecraft:levitation")
|
||||
}
|
||||
}
|
||||
/// `Slide.start`: pick a point to slide to.
|
||||
fn start_slide(m: &mut Mob, cx: &mut Cx) {
|
||||
if has(m, SHOOT)
|
||||
|| has(m, JUMP_COOLDOWN)
|
||||
|| walk_target(m)
|
||||
|| !m.on_ground
|
||||
|| m.fluids.in_water
|
||||
|| pose(m) != STANDING
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else {
|
||||
return;
|
||||
};
|
||||
let mut position: Option<Vec3> = None;
|
||||
if within_inner_circle(m, q.position)
|
||||
&& let Some(away) =
|
||||
m.default_random_pos_away(cx.w, 5, 5, [q.position.x, q.position.y, q.position.z])
|
||||
{
|
||||
let away = Vec3::new(away[0], away[1], away[2]);
|
||||
if line_of_sight(m, cx.w, away)
|
||||
&& q.position.distance_squared(away) > q.position.distance_squared(m.position)
|
||||
{
|
||||
position = Some(away);
|
||||
}
|
||||
}
|
||||
let position = position.unwrap_or_else(|| {
|
||||
if m.random.next_boolean() {
|
||||
point_behind(m, q.position, q.yaw)
|
||||
} else {
|
||||
// randomPointInMiddleCircle: stop four to eight blocks short.
|
||||
let d = q.position.subtract(m.position);
|
||||
let distance = d.length() - (8.0 + (4.0 - 8.0) * m.random.next_double());
|
||||
m.position.add_vector(d.normalize().scale(distance))
|
||||
}
|
||||
});
|
||||
m.extra.point = Some([position.x.floor(), position.y.floor(), position.z.floor()]);
|
||||
m.extra.vector[0] = 0.6;
|
||||
m.extra.vector[1] = 1.0;
|
||||
}
|
||||
/// `SlideToTargetSink` (`MoveToTargetSink`): walk to the walk target.
|
||||
fn start_walking(m: &mut Mob, cx: &mut Cx) {
|
||||
if m.extra.counter != 0 {
|
||||
return;
|
||||
}
|
||||
let Some(target) = m.extra.point else {
|
||||
return;
|
||||
};
|
||||
if m.extra.anger > 0 {
|
||||
return;
|
||||
}
|
||||
let close = m.extra.vector[1] as i32;
|
||||
let here = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
let reached = (target[0] as i32 - here[0]).abs()
|
||||
+ (target[1] as i32 - here[1]).abs()
|
||||
+ (target[2] as i32 - here[2]).abs()
|
||||
<= close;
|
||||
let speed = m.extra.vector[0];
|
||||
if !reached && m.nav_move_to(cx.w, [target[0] + 0.5, target[1], target[2] + 0.5], speed) {
|
||||
m.extra.counter = now(m) + 20 + m.random.next_int_bound(21).unwrap_or(0);
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.slide", m.center(), 1.0, 1.0));
|
||||
set_pose(m, SLIDING);
|
||||
} else {
|
||||
m.extra.point = None;
|
||||
}
|
||||
}
|
||||
fn tick_walking(m: &mut Mob, _cx: &mut Cx) {
|
||||
if m.extra.counter == 0 {
|
||||
return;
|
||||
}
|
||||
let reached = m.extra.point.is_none_or(|target| {
|
||||
let here = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
(target[0] as i32 - here[0]).abs()
|
||||
+ (target[1] as i32 - here[1]).abs()
|
||||
+ (target[2] as i32 - here[2]).abs()
|
||||
<= m.extra.vector[1] as i32
|
||||
});
|
||||
if now(m) > m.extra.counter || m.ai.nav.is_done() || reached {
|
||||
// SlideToTargetSink.stop.
|
||||
m.extra.counter = 0;
|
||||
m.extra.point = None;
|
||||
m.nav_stop();
|
||||
set_pose(m, STANDING);
|
||||
if m.ai.target.is_some() {
|
||||
remember(m, SHOOT, 60);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `RunOne` of `DoNothing(20, 100)` and `RandomStroll.stroll(0.6)`.
|
||||
fn idle_stroll(m: &mut Mob, cx: &mut Cx) {
|
||||
if m.extra.counter != 0 || walk_target(m) || m.ai.target.is_some() {
|
||||
return;
|
||||
}
|
||||
if now(m) < m.extra.counter2 {
|
||||
return;
|
||||
}
|
||||
if m.random.next_int_bound(3).unwrap_or(0) == 0 {
|
||||
m.extra.counter2 = now(m) + 20 + m.random.next_int_bound(81).unwrap_or(0);
|
||||
} else if let Some(p) = m.land_random_pos(cx.w, 10, 7) {
|
||||
m.extra.point = Some([p[0].floor(), p[1].floor(), p[2].floor()]);
|
||||
m.extra.vector[0] = 0.6;
|
||||
m.extra.vector[1] = 0.0;
|
||||
}
|
||||
}
|
||||
fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool {
|
||||
/// `LongJump.canJumpFromCurrentPosition`: not on honey, and four blocks of
|
||||
/// air or water above.
|
||||
pub(super) fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool {
|
||||
let (x, y, z) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
@@ -482,115 +51,36 @@ fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool {
|
||||
|| w.fluid(x, y + i, z) == crate::blocks::Fluid::Water
|
||||
})
|
||||
}
|
||||
/// `LongJump.snapToSurface`: the block above the surface below the point,
|
||||
/// else above the ceiling over it.
|
||||
fn snap_to_surface(w: &MobWorld, p: Vec3) -> Option<[i32; 3]> {
|
||||
let (x, z) = (p.x.floor() as i32, p.z.floor() as i32);
|
||||
let y0 = p.y.floor() as i32;
|
||||
for y in (y0 - 10..=y0).rev() {
|
||||
let top = f64::from(w.data.state(w.world.block(x, y, z)).top);
|
||||
if top > 0.0 {
|
||||
let hit = (f64::from(y) + top).min(p.y);
|
||||
return Some([x, hit.floor() as i32 + 1, z]);
|
||||
}
|
||||
/// `LongJump.snapToSurface`: the block above where a clip ten blocks down
|
||||
/// hits, else ten blocks up.
|
||||
pub(super) fn snap_to_surface(w: &MobWorld, p: Vec3) -> Option<[i32; 3]> {
|
||||
let above = |hit: Vec3| {
|
||||
[
|
||||
hit.x.floor() as i32,
|
||||
hit.y.floor() as i32 + 1,
|
||||
hit.z.floor() as i32,
|
||||
]
|
||||
};
|
||||
if let Some(hit) = w.clip_block(p, Vec3::new(p.x, p.y - 10.0, p.z)) {
|
||||
return Some(above(hit));
|
||||
}
|
||||
for y in y0..=y0 + 10 {
|
||||
if w.data.state(w.world.block(x, y, z)).top > 0.0 {
|
||||
return Some([x, y + 1, z]);
|
||||
}
|
||||
}
|
||||
None
|
||||
w.clip_block(p, Vec3::new(p.x, p.y + 10.0, p.z)).map(above)
|
||||
}
|
||||
fn dangerous_block(name: &str) -> bool {
|
||||
/// `EntityType.isBlockDangerous` for the breeze (not fire immune).
|
||||
pub(super) fn dangerous_block(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"minecraft:fire"
|
||||
| "minecraft:soul_fire"
|
||||
| "minecraft:lava"
|
||||
| "minecraft:magma_block"
|
||||
| "minecraft:campfire"
|
||||
| "minecraft:soul_campfire"
|
||||
| "minecraft:lava_cauldron"
|
||||
| "minecraft:wither_rose"
|
||||
| "minecraft:sweet_berry_bush"
|
||||
| "minecraft:cactus"
|
||||
| "minecraft:powder_snow"
|
||||
)
|
||||
}
|
||||
/// `LongJump.canRun` and `start`.
|
||||
fn start_long_jump(m: &mut Mob, cx: &mut Cx) {
|
||||
if m.extra.flag
|
||||
|| has(m, SHOOT)
|
||||
|| has(m, JUMP_COOLDOWN)
|
||||
|| walk_target(m)
|
||||
|| !can_run_long_jump(m, cx)
|
||||
{
|
||||
return;
|
||||
}
|
||||
m.extra.flag = true;
|
||||
m.extra.anim_ticks = now(m) + 200;
|
||||
if !has(m, JUMP_INHALING) {
|
||||
remember(m, JUMP_INHALING, INHALING_TICKS);
|
||||
}
|
||||
set_pose(m, INHALING);
|
||||
let at = m.center();
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.charge", at, 1.0, 1.0));
|
||||
if let Some(t) = m.extra.home {
|
||||
snap_look(
|
||||
m,
|
||||
[
|
||||
f64::from(t[0]) + 0.5,
|
||||
f64::from(t[1]) + 0.5,
|
||||
f64::from(t[2]) + 0.5,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
fn can_run_long_jump(m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !m.on_ground && !m.fluids.in_water {
|
||||
return false;
|
||||
}
|
||||
if m.fluids.water > m.eye_height() || m.fluids.in_lava {
|
||||
return false;
|
||||
}
|
||||
if m.extra.home.is_some() {
|
||||
return true;
|
||||
}
|
||||
let Some(who) = m.ai.target else {
|
||||
return false;
|
||||
};
|
||||
let Some(q) = quarry(m, cx, who) else {
|
||||
return false;
|
||||
};
|
||||
let follow = m.attrs.follow_range;
|
||||
let distance = m.position.distance(q.position);
|
||||
if distance >= follow {
|
||||
m.ai.target = None;
|
||||
return false;
|
||||
}
|
||||
if distance - 4.0 <= 0.0 || !can_jump_from_here(m, cx.w) {
|
||||
return false;
|
||||
}
|
||||
let behind = point_behind(m, q.position, q.yaw);
|
||||
let Some(target) = snap_to_surface(cx.w, behind) else {
|
||||
return false;
|
||||
};
|
||||
if dangerous_block(cx.w.block_name(target[0], target[1] - 1, target[2])) {
|
||||
return false;
|
||||
}
|
||||
let centre = Vec3::new(
|
||||
f64::from(target[0]) + 0.5,
|
||||
f64::from(target[1]) + 0.5,
|
||||
f64::from(target[2]) + 0.5,
|
||||
);
|
||||
if !line_of_sight(m, cx.w, centre)
|
||||
&& !line_of_sight(m, cx.w, centre.add_vector(Vec3::new(0.0, 4.0, 0.0)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
m.extra.home = Some(target);
|
||||
true
|
||||
}
|
||||
/// `LongJumpUtil.calculateJumpVectorForAngle` without the collision check.
|
||||
fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option<Vec3> {
|
||||
let pos = m.position;
|
||||
@@ -599,14 +89,17 @@ fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option<V
|
||||
.scale(0.5);
|
||||
let aim = target.subtract(plane);
|
||||
let d = aim.subtract(pos);
|
||||
let angrad = f64::from(angle as f32 * std::f32::consts::PI / 180.0);
|
||||
let xz = d.z.atan2(d.x);
|
||||
let r2 = d.x * d.x + d.z * d.z;
|
||||
let angrad = angle as f32 * std::f32::consts::PI / 180.0;
|
||||
// Math.atan2 is StrictMath.atan2 (fdlibm).
|
||||
let xz = horizon_core::geometry::trig::fdlibm_atan2(d.z, d.x);
|
||||
let r2 = d.x * d.x + 0.0 + d.z * d.z;
|
||||
let r = r2.sqrt();
|
||||
let g = m.kind.gravity;
|
||||
let sin2 = f64::from((2.0 * angrad as f32).sin());
|
||||
let cos_sq = angrad.cos().powi(2);
|
||||
let v0sq = r2 * g / (r * sin2 - 2.0 * d.y * cos_sq);
|
||||
let y = d.y;
|
||||
let g = m.gravity();
|
||||
let sin2 = f64::from(2.0 * angrad).sin();
|
||||
let cos_sq = f64::from(angrad).cos().powf(2.0);
|
||||
let (sin, cos) = (f64::from(angrad).sin(), f64::from(angrad).cos());
|
||||
let v0sq = r2 * g / (r * sin2 - 2.0 * y * cos_sq);
|
||||
if v0sq < 0.0 {
|
||||
return None;
|
||||
}
|
||||
@@ -614,81 +107,65 @@ fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option<V
|
||||
if v0 > f64::from(max_velocity) {
|
||||
return None;
|
||||
}
|
||||
let v0r = v0 * angrad.cos();
|
||||
let v0y = v0 * angrad.sin();
|
||||
let (v0r, v0y) = (v0 * cos, v0 * sin);
|
||||
Some(Vec3::new(v0r * xz.cos(), v0y, v0r * xz.sin()).scale(f64::from(0.95_f32)))
|
||||
}
|
||||
fn tick_long_jump(m: &mut Mob, cx: &mut Cx) {
|
||||
if !m.extra.flag {
|
||||
return;
|
||||
/// `LongJump.calculateOptimalJumpVector`: the allowed angles shuffled, the
|
||||
/// first that reaches the target.
|
||||
pub(super) fn optimal_jump_vector(m: &mut Mob, target: Vec3) -> Option<Vec3> {
|
||||
let mut angles = ALLOWED_ANGLES;
|
||||
for i in (2..=angles.len()).rev() {
|
||||
let j = m.random.next_int_bound(i as i32).unwrap_or(0) as usize;
|
||||
angles.swap(i - 1, j);
|
||||
}
|
||||
let ongoing = pose(m) != STANDING && !has(m, JUMP_COOLDOWN);
|
||||
if now(m) > m.extra.anim_ticks || !ongoing {
|
||||
// LongJump.stop.
|
||||
m.extra.flag = false;
|
||||
if matches!(pose(m), LONG_JUMPING | INHALING) {
|
||||
set_pose(m, STANDING);
|
||||
}
|
||||
m.extra.home = None;
|
||||
forget(m, JUMP_INHALING);
|
||||
m.extra.variant2 = 0;
|
||||
return;
|
||||
}
|
||||
let in_water = m.fluids.in_water;
|
||||
if !in_water && m.extra.variant2 != 0 {
|
||||
m.extra.variant2 = 0;
|
||||
}
|
||||
let finished_inhaling = !has(m, JUMP_INHALING) && pose(m) == INHALING;
|
||||
if finished_inhaling {
|
||||
let target = m.extra.home.map(|t| {
|
||||
Vec3::new(
|
||||
f64::from(t[0]) + 0.5,
|
||||
f64::from(t[1]),
|
||||
f64::from(t[2]) + 0.5,
|
||||
)
|
||||
});
|
||||
let mut angles = ALLOWED_ANGLES;
|
||||
for i in (1..angles.len()).rev() {
|
||||
let j = m.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
|
||||
angles.swap(i, j);
|
||||
}
|
||||
let max = 0.058_333_334_f32 * m.attrs.follow_range as f32;
|
||||
let v = target.and_then(|t| angles.iter().find_map(|&a| jump_vector(m, t, max, a)));
|
||||
let Some(v) = v else {
|
||||
set_pose(m, STANDING);
|
||||
return;
|
||||
};
|
||||
if in_water {
|
||||
m.extra.variant2 = 1;
|
||||
}
|
||||
let at = m.center();
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.jump", at, 1.0, 1.0));
|
||||
set_pose(m, LONG_JUMPING);
|
||||
m.yaw = m.body_yaw;
|
||||
m.velocity = v;
|
||||
m.on_ground = false;
|
||||
return;
|
||||
}
|
||||
let landed_in_water = in_water && m.extra.variant2 == 0;
|
||||
if pose(m) == LONG_JUMPING && (m.on_ground || landed_in_water) {
|
||||
let at = m.center();
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0));
|
||||
set_pose(m, STANDING);
|
||||
let hurt = m
|
||||
.last_damage
|
||||
.is_some_and(|(_, t)| i64::from(m.age) - t <= 40);
|
||||
remember(m, JUMP_COOLDOWN, if hurt { 2 } else { 10 });
|
||||
remember(m, SHOOT, 100);
|
||||
let max = 0.058_333_334_f32 * m.attrs.follow_range as f32;
|
||||
let v = angles
|
||||
.iter()
|
||||
.find_map(|&a| jump_vector(m, target, max, a))?;
|
||||
if m.has_effect("minecraft:jump_boost") {
|
||||
let amp = m
|
||||
.extra
|
||||
.effects
|
||||
.iter()
|
||||
.find(|e| e.0 == "minecraft:jump_boost")
|
||||
.map_or(0, |e| e.2);
|
||||
// LivingEntity.getJumpBoostPower
|
||||
let boost = f64::from(0.1_f32 * (amp + 1) as f32);
|
||||
return Some(v.add_vector(Vec3::new(0.0, v.normalize().y * boost, 0.0)));
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
/// Whether `Breeze.shouldDiscardFriction` applies (a long jump in the air).
|
||||
pub fn discards_friction(m: &Mob) -> bool {
|
||||
m.species() == Species::Breeze && pose(m) == LONG_JUMPING
|
||||
}
|
||||
/// `Breeze.tick` and the client's pose-driven animation states.
|
||||
pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
/// The random draws of `Breeze.tick` before `super.tick()`: the ground
|
||||
/// particle count (standing, shooting or inhaling) and the whirl sound clock
|
||||
/// (`playWhirlSound` is a local sound, heard on the client only).
|
||||
pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if matches!(pose(m), SHOOTING | INHALING | STANDING) {
|
||||
// emitGroundParticles(1 + random.nextInt(1))
|
||||
let _ = m.random.next_int_bound(1);
|
||||
}
|
||||
if m.extra.vector[2] == 0.0 {
|
||||
m.extra.vector[2] = f64::from(m.random.next_int_between_inclusive(1, 80).unwrap_or(1));
|
||||
} else {
|
||||
m.extra.vector[2] -= 1.0;
|
||||
}
|
||||
if m.extra.vector[2] == 0.0 {
|
||||
let pitch = 0.7 + 0.4 * m.random.next_float();
|
||||
let volume = 0.8 + 0.2 * m.random.next_float();
|
||||
events.push(MobEvent::LocalSound(
|
||||
"entity.breeze.whirl",
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
volume,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
}
|
||||
/// The client's pose-driven animation states (`onSyncedDataUpdated` and
|
||||
/// `Breeze.tick`).
|
||||
pub fn ai_step(m: &mut Mob) {
|
||||
let age = m.age as f32;
|
||||
let current = pose(m);
|
||||
if current != m.extra.variant {
|
||||
@@ -714,24 +191,9 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.anim.states[3].start(age);
|
||||
m.anim.states[2].stop();
|
||||
}
|
||||
// The whirl sound.
|
||||
if m.extra.vector[2] <= 0.0 {
|
||||
m.extra.vector[2] = f64::from(1 + m.random.next_int_bound(80).unwrap_or(0));
|
||||
} else {
|
||||
m.extra.vector[2] -= 1.0;
|
||||
if m.extra.vector[2] <= 0.0 {
|
||||
let pitch = 0.7 + 0.4 * m.random.next_float();
|
||||
let volume = 0.8 + 0.2 * m.random.next_float();
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.breeze.whirl",
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
volume,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Breeze.playAmbientSound` and its sound selection.
|
||||
/// `Breeze.playAmbientSound` (a local sound at volume and pitch 1) and its
|
||||
/// sound selection.
|
||||
pub fn ambient(m: &Mob) -> Option<&'static str> {
|
||||
if m.ai.target.is_some() && m.on_ground {
|
||||
return None;
|
||||
@@ -763,21 +225,6 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Anim
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_memory_is_present_for_its_ttl_plus_the_tick_it_was_set() {
|
||||
// setMemoryWithExpiry(15) at tick T: present T through T + 15.
|
||||
let mut v = 16;
|
||||
let mut present = 1;
|
||||
for _ in 0..30 {
|
||||
if v > 0 {
|
||||
v -= 1;
|
||||
}
|
||||
if v > 0 {
|
||||
present += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(present, 16);
|
||||
}
|
||||
#[test]
|
||||
fn the_highest_arc_reaches_a_target_within_range() {
|
||||
// Angle 80 degrees: v0^2 = r^2 g / (r sin 2a - 2 y cos^2 a).
|
||||
|
||||
@@ -55,20 +55,21 @@ fn first_is_leashed(cx: &Cx, caravan: u32, leashed: bool, counter: i32) -> bool
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FollowCaravan {
|
||||
speed: f64,
|
||||
base_speed: f64,
|
||||
dist_check: i32,
|
||||
}
|
||||
impl FollowCaravan {
|
||||
pub fn new(speed: f64) -> Self {
|
||||
Self {
|
||||
speed,
|
||||
base_speed: speed,
|
||||
dist_check: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for FollowCaravan {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"LlamaFollowCaravanGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
super::goals::MOVE
|
||||
}
|
||||
@@ -158,7 +159,8 @@ impl Goal for FollowCaravan {
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.extra.ints[1] = 0;
|
||||
self.speed = self.base_speed;
|
||||
// A double 2.1 here, while the llama built it with 2.1F.
|
||||
self.speed = 2.1;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let caravan = head_of(m);
|
||||
@@ -265,7 +267,7 @@ pub fn trader_llama_tick(m: &mut Mob, w: &MobWorld) {
|
||||
}
|
||||
m.extra.ints[0] = trader.unwrap_or(m.extra.ints[0]) - 1;
|
||||
if m.extra.ints[0] <= 0 {
|
||||
m.extra.leash = None;
|
||||
super::leash::remove(m);
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,8 @@ pub enum LookKind {
|
||||
SmoothSwimming(f32),
|
||||
/// Look controls that never reset pitch (e.g. ghasts keep their own).
|
||||
Fixed,
|
||||
/// `HappyGhast.HappyGhastLookControl`.
|
||||
HappyGhast,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LookControl {
|
||||
@@ -307,8 +309,12 @@ impl Mob {
|
||||
/// LookControl.tick (and SmoothSwimmingLookControl).
|
||||
pub fn look_control_tick(&mut self) {
|
||||
let look = self.ai.look.clone();
|
||||
if look.kind == LookKind::HappyGhast {
|
||||
return super::happy_ghast::look_control(self);
|
||||
}
|
||||
let (x_d, y_d) = self.look_angles(look.wanted);
|
||||
match look.kind {
|
||||
LookKind::HappyGhast => {}
|
||||
LookKind::SmoothSwimming(max) => {
|
||||
if look.cooldown > 0 {
|
||||
self.ai.look.cooldown -= 1;
|
||||
|
||||
@@ -14,8 +14,8 @@ use std::collections::HashMap;
|
||||
|
||||
// Copper golem state: `variant` the weathering (0 unaffected .. 3 oxidized),
|
||||
// `variant3` the `CopperGolemState`, `main_hand` with `ints[1]` the carried
|
||||
// stack, `legs` the antenna block, `egg_time` the next weathering tick (-1
|
||||
// unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest
|
||||
// stack, the saddle slot the antenna (`EQUIPMENT_SLOT_ANTENNA`), `vector[0]`
|
||||
// the next weathering tick (-1 unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest
|
||||
// being served with `positions` the visited chests, `point` where it walks,
|
||||
// `scratch` = [transport phase, ticks since reaching the target, interaction
|
||||
// state, transport cooldown ticks]. AnimationState slots: idle (0), getting an
|
||||
@@ -32,7 +32,8 @@ pub fn register(m: &mut Mob) {
|
||||
m.ai.nav.required_path_length = 48.0;
|
||||
m.ai.nav.can_open_doors = true;
|
||||
m.persistent = true;
|
||||
m.extra.egg_time = -1;
|
||||
// nextWeatheringTick starts unset (-1); waxed is -2.
|
||||
m.extra.vector[0] = -1.0;
|
||||
m.extra.scratch[3] = 60 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Panic::new(1.5));
|
||||
@@ -44,7 +45,10 @@ pub fn register(m: &mut Mob) {
|
||||
pub fn texture(m: &Mob) -> String {
|
||||
match m.extra.variant {
|
||||
0 => "entity/copper_golem/copper_golem".into(),
|
||||
n => format!("entity/copper_golem/copper_golem_{}", WEATHER[n.min(3) as usize]),
|
||||
n => format!(
|
||||
"entity/copper_golem/copper_golem_{}",
|
||||
WEATHER[n.min(3) as usize]
|
||||
),
|
||||
}
|
||||
}
|
||||
pub fn eye_texture(m: &Mob) -> String {
|
||||
@@ -101,8 +105,12 @@ impl Goal for Serve {
|
||||
]);
|
||||
match m.extra.point {
|
||||
Some(p) => {
|
||||
if m.ai.nav.is_done() || m.age % 10 == 0 {
|
||||
let block = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
|
||||
if m.ai.nav.is_done() || m.age.is_multiple_of(10) {
|
||||
let block = [
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
];
|
||||
let path = m.create_path_to(cx.w, block, 0);
|
||||
m.nav_move_to_path(path, 1.0);
|
||||
}
|
||||
@@ -179,12 +187,13 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
match state {
|
||||
IDLE => {
|
||||
interaction(st, 0);
|
||||
if m.extra.ints[0] == m.age {
|
||||
let tick = m.age as i32;
|
||||
if m.extra.ints[0] == tick {
|
||||
st[0].start(age);
|
||||
} else if m.extra.ints[0] == 0 {
|
||||
m.extra.ints[0] = m.age + 200 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
m.extra.ints[0] = tick + 200 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
}
|
||||
if m.age == m.extra.ints[0] + 10 {
|
||||
if tick == m.extra.ints[0] + 10 {
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
events.push(MobEvent::Sound(sound(m, "spin"), at, 1.0, 1.0));
|
||||
m.extra.ints[0] = 0;
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at
|
||||
//! them, wake up when one looks from within 12 blocks, then hunt the nearest
|
||||
//! visible player and hit every 40 ticks. One bound to a creaking heart takes
|
||||
//! no damage (it only sways and hurts the heart's resin spreader), dies when
|
||||
//! the heart no longer protects it and falls apart with the heart.
|
||||
//! Creakings (`Creaking`): they freeze while any player looks at them, wake
|
||||
//! up when one looks from within 12 blocks, then hunt the nearest visible
|
||||
//! player and hit every 40 ticks (the brain, `CreakingAi`, is in
|
||||
//! `monster_brain`). One bound to a creaking heart takes no damage (it only
|
||||
//! sways and hurts the heart's resin spreader), dies when the heart no
|
||||
//! longer protects it and falls apart with the heart.
|
||||
use super::{
|
||||
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
|
||||
anim::{Poses, State},
|
||||
goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone},
|
||||
keyframes::Animation,
|
||||
monster_brain,
|
||||
path::PathType,
|
||||
};
|
||||
use crate::containers::BlockEntity;
|
||||
@@ -33,13 +34,10 @@ const ATTACK_TICKS: i32 = 15;
|
||||
/// `Creaking.TWITCH_DEATH_DURATION`.
|
||||
const TWITCH_TICKS: i32 = 45;
|
||||
|
||||
/// `Creaking`'s constructor: no goals (the brain thinks), a navigation that
|
||||
/// floats.
|
||||
pub fn register(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(2, MeleeAttack::new(1.0, false).interval(40));
|
||||
g.add(5, Stroll::avoiding_water(0.3));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
m.ai.targets.add(1, HuntPlayer);
|
||||
m.ai.nav.can_float = true;
|
||||
}
|
||||
/// Bound to a heart (`getHomePos() != null`).
|
||||
pub fn heart_bound(m: &Mob) -> bool {
|
||||
@@ -132,10 +130,29 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
|
||||
m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 };
|
||||
false
|
||||
}
|
||||
/// `Creaking.doHurtTarget` extras: the attack animation and sound.
|
||||
pub fn on_attack(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
/// The rest of `Creaking.hurtServer` for a heart-bound creaking, run by the
|
||||
/// host right after the damage: whether its heart still protects it, and
|
||||
/// whether a player is to blame (the heart then calls `creakingHurt`). The
|
||||
/// caller plays [`sway`] after the heart's reaction.
|
||||
pub fn take_hurt(m: &mut Mob, w: &MobWorld) -> Option<([i32; 3], bool)> {
|
||||
if m.extra.counter & HURT == 0 {
|
||||
return None;
|
||||
}
|
||||
let by_player = m.extra.counter & HURT_BY_PLAYER != 0;
|
||||
m.extra.counter &= !(HURT | HURT_BY_PLAYER);
|
||||
let home = m.extra.home?;
|
||||
protected(m, w).then_some((home, by_player))
|
||||
}
|
||||
/// `Mob.playHurtSound` of a heart-bound creaking: the ambient sound clock
|
||||
/// restarts and it sways.
|
||||
pub fn sway(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.ambient_timer = -m.kind.ambient_interval;
|
||||
m.voice("entity.creaking.sway", events);
|
||||
}
|
||||
/// `Creaking.doHurtTarget`: the attack animation (the sound is the
|
||||
/// `playAttackSound` that ends `Mob.doHurtTarget`).
|
||||
pub fn on_attack(m: &mut Mob, _events: &mut Vec<MobEvent>) {
|
||||
m.extra.ints[ATTACKING] = ATTACK_TICKS;
|
||||
m.voice("entity.creaking.attack", events);
|
||||
}
|
||||
/// The heart this creaking is bound to protects it (`isProtector`); a link
|
||||
/// read from a save is trusted until the heart resolves it.
|
||||
@@ -178,7 +195,7 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
id: m.id,
|
||||
});
|
||||
}
|
||||
m.voice("entity.creaking.sway", events);
|
||||
sway(m, events);
|
||||
}
|
||||
m.extra.counter &= !(HURT | HURT_BY_PLAYER);
|
||||
}
|
||||
@@ -215,71 +232,84 @@ pub fn stop_in_place(m: &mut Mob) {
|
||||
m.ai.yya = 0.0;
|
||||
m.ai.zza = 0.0;
|
||||
m.ai.speed = 0.0;
|
||||
m.velocity = horizon_core::geometry::Vec3::ZERO;
|
||||
m.extra.leash_spin = 0.0;
|
||||
}
|
||||
/// `Creaking.activate`.
|
||||
fn activate(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.ai.target = Some(Who::Player);
|
||||
monster_brain::set_attack_target(m, Some(Who::Player));
|
||||
m.voice("entity.creaking.activate", events);
|
||||
m.extra.flag = true;
|
||||
}
|
||||
/// `Creaking.deactivate`.
|
||||
fn deactivate(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
m.ai.target = None;
|
||||
monster_brain::set_attack_target(m, None);
|
||||
m.voice("entity.creaking.deactivate", events);
|
||||
m.extra.flag = false;
|
||||
}
|
||||
/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`.
|
||||
/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5,
|
||||
/// (eyeY + y) / 2)`: within the player's view cone and seen through
|
||||
/// transparent blocks.
|
||||
fn looked_at_by(m: &Mob, w: &MobWorld) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
let look = p.look;
|
||||
let look = normalize(p.look);
|
||||
let eye = m.eye_y();
|
||||
[eye, m.position.y + 0.5, (eye + m.position.y) / 2.0]
|
||||
.into_iter()
|
||||
.any(|y| {
|
||||
let d = [
|
||||
let d = normalize([
|
||||
m.position.x - p.position.x,
|
||||
y - p.eye[1],
|
||||
m.position.z - p.position.z,
|
||||
];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
if len < 1.0e-6 {
|
||||
return true;
|
||||
]);
|
||||
let dot = look[0] * d[0] + look[1] * d[1] + look[2] * d[2];
|
||||
if dot <= 0.5 {
|
||||
return false;
|
||||
}
|
||||
let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len;
|
||||
dot > 0.5
|
||||
&& w.line_of_sight(
|
||||
Vec3::new(p.eye[0], p.eye[1], p.eye[2]),
|
||||
Vec3::new(m.position.x, y, m.position.z),
|
||||
)
|
||||
// Player.hasLineOfSight(this, VISUAL, NONE, y).
|
||||
let from = Vec3::new(p.position.x, p.eye[1], p.position.z);
|
||||
let to = Vec3::new(m.position.x, y, m.position.z);
|
||||
to.distance(from) <= 128.0 && w.visual_clear_between(from, to)
|
||||
})
|
||||
}
|
||||
/// `Vec3.normalize`.
|
||||
fn normalize(v: [f64; 3]) -> [f64; 3] {
|
||||
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
|
||||
if len < f64::from(1.0e-5_f32) {
|
||||
[0.0; 3]
|
||||
} else {
|
||||
[v[0] / len, v[1] / len, v[2] / len]
|
||||
}
|
||||
}
|
||||
/// `Creaking.checkCanMove`: false while looked at; also wakes and calms it.
|
||||
fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
let players = monster_brain::nearest_players(m);
|
||||
let active = is_active(m);
|
||||
// NEAREST_PLAYERS: players within the follow range.
|
||||
let near = w.player.as_ref().filter(|p| {
|
||||
let d = Vec3::new(p.position.x, p.position.y, p.position.z);
|
||||
m.distance_sqr(d) < 32.0 * 32.0
|
||||
});
|
||||
let Some(p) = near else {
|
||||
if players.is_empty() {
|
||||
if active {
|
||||
deactivate(m, events);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// canAttack: alive and not creative or spectator.
|
||||
let attackable = p.alive && !p.creative;
|
||||
if attackable {
|
||||
// GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake.
|
||||
let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin");
|
||||
if (!active || !disguised) && looked_at_by(m, w) {
|
||||
if active {
|
||||
return false;
|
||||
}
|
||||
if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ {
|
||||
activate(m, events);
|
||||
return false;
|
||||
}
|
||||
let mut potential = false;
|
||||
if let Some(p) = w.player.as_ref().filter(|_| players.contains(&Who::Player)) {
|
||||
// canAttack (not creative, spectator or dead) and not allied.
|
||||
if p.alive && !p.creative && !p.spectator {
|
||||
potential = true;
|
||||
// GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake.
|
||||
let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin");
|
||||
if (!active || !disguised) && looked_at_by(m, w) {
|
||||
if active {
|
||||
return false;
|
||||
}
|
||||
if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ {
|
||||
activate(m, events);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if active {
|
||||
}
|
||||
if !potential && active {
|
||||
deactivate(m, events);
|
||||
}
|
||||
true
|
||||
@@ -292,12 +322,13 @@ pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool {
|
||||
};
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
// AABB.contains: the far faces are outside.
|
||||
let inside = eye[0] >= lo.x
|
||||
&& eye[0] <= hi.x
|
||||
&& eye[0] < hi.x
|
||||
&& eye[1] >= lo.y
|
||||
&& eye[1] <= hi.y
|
||||
&& eye[1] < hi.y
|
||||
&& eye[2] >= lo.z
|
||||
&& eye[2] <= hi.z;
|
||||
&& eye[2] < hi.z;
|
||||
if inside {
|
||||
m.extra.ints[STUCK] += 1;
|
||||
m.extra.ints[STUCK] > 4
|
||||
@@ -306,39 +337,6 @@ pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
/// The nearest attackable player the creaking can see.
|
||||
fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else {
|
||||
return false;
|
||||
};
|
||||
let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2);
|
||||
p.alive && !p.creative && near && m.sees(cx.w, Who::Player)
|
||||
}
|
||||
/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the
|
||||
/// nearest visible player.
|
||||
#[derive(Clone, Debug)]
|
||||
struct HuntPlayer;
|
||||
impl Goal for HuntPlayer {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
TARGET
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !is_active(m) || !sees_attackable_player(m, cx) {
|
||||
return false;
|
||||
}
|
||||
m.ai.target = Some(Who::Player);
|
||||
true
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
if m.ai.target == Some(Who::Player) {
|
||||
m.ai.target = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `CreakingModel.setupAnim`.
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Animation>) {
|
||||
p.xrot("head", s.x_rot.to_radians());
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
//! The creaking heart's block entity (`CreakingHeartBlockEntity`): at night
|
||||
//! an awake heart in a pale oak trunk spawns a creaking that protects it
|
||||
//! (`SpawnUtil.trySpawnMob`), lets it go by day, when it strays or when a
|
||||
//! player is stuck in it, and when that creaking is hurt by a player emits
|
||||
//! trails and spreads resin over the logs. The game and the mob AI probe
|
||||
//! both tick hearts through this module; the host applies the block changes
|
||||
//! and plays what it reports.
|
||||
use super::{Mob, MobEvent, MobType, MobWorld, creaking};
|
||||
use crate::{collisions::SceneCollisions, containers::CreakingHeart};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`.
|
||||
pub const ORANGE: u32 = 16_545_810;
|
||||
pub const GRAY: u32 = 6_250_335;
|
||||
/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`.
|
||||
const TOO_FAR: f64 = 34.0;
|
||||
/// `Direction.values()`: down, up, north, south, west, east.
|
||||
const DIRECTIONS: [[i32; 3]; 6] = [
|
||||
[0, -1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, -1],
|
||||
[0, 0, 1],
|
||||
[-1, 0, 0],
|
||||
[1, 0, 0],
|
||||
];
|
||||
const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
|
||||
|
||||
/// What a heart's tick did, for its host to apply.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum HeartEvent {
|
||||
/// `Level.setBlockAndUpdate`.
|
||||
SetBlock([i32; 3], BlockStateId),
|
||||
/// `Level.playSound(null, ...)`: heard by everyone.
|
||||
Sound(&'static str, [f64; 3], f32, f32),
|
||||
/// A `TrailParticleOption` sent from `at` towards `target`.
|
||||
Trail {
|
||||
at: [f64; 3],
|
||||
target: [f64; 3],
|
||||
color: u32,
|
||||
duration: i32,
|
||||
},
|
||||
/// `updateNeighbourForOutputSignal`: comparators read the new signal.
|
||||
OutputChanged([i32; 3]),
|
||||
/// A mob's own sounds and effects (the spawned creaking's voice, a
|
||||
/// creaking falling apart).
|
||||
Mob(MobEvent),
|
||||
}
|
||||
|
||||
/// The mobs a heart sees and the creakings it spawns.
|
||||
pub trait HeartHost {
|
||||
fn mob(&self, id: u32) -> Option<&Mob>;
|
||||
fn mob_mut(&mut self, id: u32) -> Option<&mut Mob>;
|
||||
/// The loaded mob with this UUID.
|
||||
fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option<u32>;
|
||||
fn uuid_for(&mut self, id: u32) -> [i32; 4];
|
||||
/// The creaking's entity type.
|
||||
fn creaking_type(&self) -> Option<Arc<MobType>>;
|
||||
/// A new mob of the type (the next entity id, its random seeded).
|
||||
fn create_mob(&mut self, kind: Arc<MobType>, at: Vec3) -> Mob;
|
||||
/// `Level.addFreshEntity`.
|
||||
fn add_mob(&mut self, m: Mob);
|
||||
/// `ServerLevel.isSpawningMonsters` (rules and difficulty).
|
||||
fn spawning_monsters(&self) -> bool;
|
||||
}
|
||||
|
||||
/// Block reads during a tick see the tick's own changes.
|
||||
struct Blocks<'a, 'w> {
|
||||
w: &'a MobWorld<'w>,
|
||||
changed: Vec<([i32; 3], BlockStateId)>,
|
||||
}
|
||||
impl Blocks<'_, '_> {
|
||||
fn get(&self, p: [i32; 3]) -> BlockStateId {
|
||||
self.changed
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(q, _)| *q == p)
|
||||
.map_or_else(|| self.w.world.block(p[0], p[1], p[2]), |(_, s)| *s)
|
||||
}
|
||||
fn set(&mut self, p: [i32; 3], s: BlockStateId, out: &mut Vec<HeartEvent>) {
|
||||
self.changed.push((p, s));
|
||||
out.push(HeartEvent::SetBlock(p, s));
|
||||
}
|
||||
fn name(&self, s: BlockStateId) -> &str {
|
||||
&self.w.facts.get(s).name
|
||||
}
|
||||
fn prop(&self, s: BlockStateId, key: &str) -> Option<String> {
|
||||
self.w
|
||||
.registry
|
||||
.state(s)
|
||||
.and_then(|st| st.properties.get(key).cloned())
|
||||
}
|
||||
fn with_prop(&self, s: BlockStateId, key: &str, value: &str) -> Option<BlockStateId> {
|
||||
let mut st = self.w.registry.state(s)?.clone();
|
||||
st.properties.insert(key.to_owned(), value.to_owned());
|
||||
self.w.registry.resolve(&st).ok()
|
||||
}
|
||||
fn is_pale_oak_log(&self, p: [i32; 3]) -> bool {
|
||||
let s = self.get(p);
|
||||
self.w.has_tag("minecraft:pale_oak_logs", self.name(s))
|
||||
}
|
||||
}
|
||||
|
||||
/// `EnvironmentAttributes.CREAKING_ACTIVE`: the overworld's night, from
|
||||
/// 12600 to 23400.
|
||||
pub fn creaking_active(w: &MobWorld) -> bool {
|
||||
!w.nether && !w.end && (12600..23401).contains(&w.day_time.rem_euclid(24000))
|
||||
}
|
||||
/// `CreakingHeartBlock.hasRequiredLogs`: pale oak logs on both ends of the
|
||||
/// heart's axis, along the same axis.
|
||||
fn has_required_logs(b: &Blocks, state: BlockStateId, pos: [i32; 3]) -> bool {
|
||||
let axis = b.prop(state, "axis").unwrap_or_else(|| "y".into());
|
||||
let dirs: [usize; 2] = match axis.as_str() {
|
||||
"x" => [4, 5],
|
||||
"z" => [2, 3],
|
||||
_ => [0, 1],
|
||||
};
|
||||
dirs.iter().all(|&d| {
|
||||
let n = [
|
||||
pos[0] + DIRECTIONS[d][0],
|
||||
pos[1] + DIRECTIONS[d][1],
|
||||
pos[2] + DIRECTIONS[d][2],
|
||||
];
|
||||
let s = b.get(n);
|
||||
b.w.has_tag("minecraft:pale_oak_logs", b.name(s))
|
||||
&& b.prop(s, "axis").as_deref() == Some(axis.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
/// `getCreakingProtector`: the protector's entity, resolving a UUID read
|
||||
/// from a save (forgotten 30 ticks after the heart came back unresolved).
|
||||
pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option<u32> {
|
||||
let (id, uuid) = heart.creaking?;
|
||||
if let Some(id) = id {
|
||||
if host.mob(id).is_some_and(|m| !m.removed) {
|
||||
return Some(id);
|
||||
}
|
||||
// setCreakingInfo(uuid)
|
||||
heart.creaking = Some((None, uuid));
|
||||
heart.ticks_existed = 0;
|
||||
}
|
||||
if let Some(id) = host.mob_for_uuid(uuid) {
|
||||
heart.creaking = Some((Some(id), uuid));
|
||||
return Some(id);
|
||||
}
|
||||
if heart.ticks_existed >= 30 {
|
||||
heart.creaking = None;
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `isProtector`.
|
||||
pub fn is_protector(heart: &mut CreakingHeart, host: &impl HeartHost, id: u32) -> bool {
|
||||
protector(heart, host) == Some(id)
|
||||
}
|
||||
fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 {
|
||||
protector(heart, host)
|
||||
.and_then(|id| host.mob(id))
|
||||
.map_or(0.0, |m| {
|
||||
let at = Vec3::new(
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
);
|
||||
m.distance_sqr(at).sqrt()
|
||||
})
|
||||
}
|
||||
/// `computeAnalogOutputSignal`.
|
||||
fn output_signal(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> i32 {
|
||||
if heart.creaking.is_none() || protector(heart, host).is_none() {
|
||||
return 0;
|
||||
}
|
||||
let scaled = distance_to_creaking(heart, pos, host).clamp(0.0, 32.0) / 32.0;
|
||||
15 - (scaled * 15.0).floor() as i32
|
||||
}
|
||||
/// `removeProtector`: the creaking falls apart (`tearDown`), or with a
|
||||
/// damage source (`by_player`) twitches to death.
|
||||
pub fn remove_protector(
|
||||
heart: &mut CreakingHeart,
|
||||
host: &mut impl HeartHost,
|
||||
by_player: bool,
|
||||
out: &mut Vec<HeartEvent>,
|
||||
) {
|
||||
let Some(id) = protector(heart, host) else {
|
||||
return;
|
||||
};
|
||||
if let Some(m) = host.mob_mut(id) {
|
||||
let mut events = Vec::new();
|
||||
if by_player {
|
||||
// creakingDeathEffects, setTearingDown, setHealth(0).
|
||||
creaking::set_tearing_down(m);
|
||||
m.health = 0.0;
|
||||
m.voice("entity.creaking.twitch", &mut events);
|
||||
} else {
|
||||
creaking::tear_down(m, &mut events);
|
||||
}
|
||||
out.extend(events.into_iter().map(HeartEvent::Mob));
|
||||
}
|
||||
heart.creaking = None;
|
||||
}
|
||||
/// `emitParticles`: trails between the protector and the heart.
|
||||
fn emit_particles(
|
||||
heart: &mut CreakingHeart,
|
||||
pos: [i32; 3],
|
||||
count: i32,
|
||||
towards: bool,
|
||||
lr: &mut LegacyRandom,
|
||||
host: &impl HeartHost,
|
||||
out: &mut Vec<HeartEvent>,
|
||||
) {
|
||||
let Some(b) = protector(heart, host)
|
||||
.and_then(|id| host.mob(id))
|
||||
.map(Mob::bounds)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
for _ in 0..count {
|
||||
let mut source = [
|
||||
lo.x + lr.next_double() * (hi.x - lo.x),
|
||||
lo.y + lr.next_double() * (hi.y - lo.y),
|
||||
lo.z + lr.next_double() * (hi.z - lo.z),
|
||||
];
|
||||
let mut destination = [
|
||||
f64::from(pos[0]) + lr.next_double(),
|
||||
f64::from(pos[1]) + lr.next_double(),
|
||||
f64::from(pos[2]) + lr.next_double(),
|
||||
];
|
||||
if towards {
|
||||
std::mem::swap(&mut source, &mut destination);
|
||||
}
|
||||
let duration = lr.next_int_bound(40).unwrap_or(0) + 10;
|
||||
out.push(HeartEvent::Trail {
|
||||
at: source,
|
||||
target: destination,
|
||||
color: if towards { ORANGE } else { GRAY },
|
||||
duration,
|
||||
});
|
||||
}
|
||||
}
|
||||
/// `Util.shuffledCopy(Direction.values(), random)`.
|
||||
fn shuffled_directions(lr: &mut LegacyRandom) -> [usize; 6] {
|
||||
let mut order = [0, 1, 2, 3, 4, 5];
|
||||
for i in (2..=6).rev() {
|
||||
let j = lr.next_int_bound(i as i32).unwrap_or(0) as usize;
|
||||
order.swap(i - 1, j);
|
||||
}
|
||||
order
|
||||
}
|
||||
fn offset(p: [i32; 3], d: usize) -> [i32; 3] {
|
||||
[
|
||||
p[0] + DIRECTIONS[d][0],
|
||||
p[1] + DIRECTIONS[d][1],
|
||||
p[2] + DIRECTIONS[d][2],
|
||||
]
|
||||
}
|
||||
/// `spreadResin`: a resin clump on the first log face found within two steps
|
||||
/// of pale oak logs (`BlockPos.breadthFirstTraversal(pos, 2, 64, ...)`).
|
||||
fn spread_resin(
|
||||
b: &mut Blocks,
|
||||
pos: [i32; 3],
|
||||
lr: &mut LegacyRandom,
|
||||
out: &mut Vec<HeartEvent>,
|
||||
) -> Option<[i32; 3]> {
|
||||
let mut visited: Vec<[i32; 3]> = Vec::new();
|
||||
let mut queue: std::collections::VecDeque<([i32; 3], i32)> = Default::default();
|
||||
queue.push_back((pos, 0));
|
||||
let mut count = 0;
|
||||
while let Some((current, depth)) = queue.pop_front() {
|
||||
if visited.contains(¤t) {
|
||||
continue;
|
||||
}
|
||||
visited.push(current);
|
||||
// The node visitor.
|
||||
if b.is_pale_oak_log(current) {
|
||||
for d in shuffled_directions(lr) {
|
||||
let n = offset(current, d);
|
||||
let mut neighbour = b.get(n);
|
||||
let opposite = d ^ 1;
|
||||
let facts = b.w.facts.get(neighbour);
|
||||
if b.w.facts.is_air(neighbour) {
|
||||
neighbour = b.w.registry.default_state("minecraft:resin_clump")?;
|
||||
} else if &*facts.name == "minecraft:water"
|
||||
&& facts.fluid_level == 8
|
||||
&& !facts.fluid_falling
|
||||
{
|
||||
let clump = b.w.registry.default_state("minecraft:resin_clump")?;
|
||||
neighbour = b.with_prop(clump, "waterlogged", "true")?;
|
||||
}
|
||||
if b.name(neighbour) == "minecraft:resin_clump"
|
||||
&& b.prop(neighbour, FACE_NAMES[opposite]).as_deref() != Some("true")
|
||||
{
|
||||
let placed = b.with_prop(neighbour, FACE_NAMES[opposite], "true")?;
|
||||
b.set(n, placed, out);
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
count += 1;
|
||||
if count >= 64 {
|
||||
return None;
|
||||
}
|
||||
if depth < 2 {
|
||||
// The neighbour provider: adjacent pale oak logs.
|
||||
for d in shuffled_directions(lr) {
|
||||
let n = offset(current, d);
|
||||
if b.is_pale_oak_log(n) {
|
||||
queue.push_back((n, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `creakingHurt`: a player hurt the protector.
|
||||
pub fn creaking_hurt(
|
||||
heart: &mut CreakingHeart,
|
||||
pos: [i32; 3],
|
||||
w: &MobWorld,
|
||||
lr: &mut LegacyRandom,
|
||||
host: &mut impl HeartHost,
|
||||
out: &mut Vec<HeartEvent>,
|
||||
) {
|
||||
let Some(id) = protector(heart, host) else {
|
||||
return;
|
||||
};
|
||||
if heart.emitter > 0 {
|
||||
return;
|
||||
}
|
||||
emit_particles(heart, pos, 20, false, lr, host, out);
|
||||
let mut b = Blocks {
|
||||
w,
|
||||
changed: Vec::new(),
|
||||
};
|
||||
let state = b.get(pos);
|
||||
if b.prop(state, "creaking_heart_state").as_deref() == Some("awake") {
|
||||
let clumps = lr.next_int_between_inclusive(2, 3).unwrap_or(2);
|
||||
for _ in 0..clumps {
|
||||
if let Some(at) = spread_resin(&mut b, pos, lr, out) {
|
||||
out.push(HeartEvent::Sound("block.resin.place", centre(at), 1.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
heart.emitter = 100;
|
||||
heart.emitter_target = host.mob(id).map(Mob::center);
|
||||
}
|
||||
fn centre(p: [i32; 3]) -> [f64; 3] {
|
||||
[
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]) + 0.5,
|
||||
f64::from(p[2]) + 0.5,
|
||||
]
|
||||
}
|
||||
|
||||
/// `SpawnUtil.Strategy.ON_TOP_OF_COLLIDER_NO_LEAVES`.
|
||||
fn can_spawn_on(b: &Blocks, pos: [i32; 3], state: BlockStateId, above: BlockStateId) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: b.w.world,
|
||||
binding: b.w.collision,
|
||||
};
|
||||
let above_pos = [pos[0], pos[1] + 1, pos[2]];
|
||||
let above_empty =
|
||||
b.w.collision
|
||||
.collision_shape(&mut scene, above, above_pos)
|
||||
.is_ok_and(|s| s.is_empty());
|
||||
above_empty
|
||||
&& !b.w.has_tag("minecraft:leaves", b.name(state))
|
||||
&& b.w.facts.get(state).sturdy_full & (1 << 1) != 0
|
||||
}
|
||||
/// `SpawnUtil.trySpawnMob(CREAKING, SPAWNER, level, pos, 5, 16, 8,
|
||||
/// ON_TOP_OF_COLLIDER_NO_LEAVES, true)` and `spawnProtector`.
|
||||
fn spawn_protector(
|
||||
pos: [i32; 3],
|
||||
w: &MobWorld,
|
||||
lr: &mut LegacyRandom,
|
||||
host: &mut impl HeartHost,
|
||||
out: &mut Vec<HeartEvent>,
|
||||
) -> Option<u32> {
|
||||
let kind = host.creaking_type()?;
|
||||
let b = Blocks {
|
||||
w,
|
||||
changed: Vec::new(),
|
||||
};
|
||||
for _ in 0..5 {
|
||||
let dx = lr.next_int_between_inclusive(-16, 16).unwrap_or(0);
|
||||
let dz = lr.next_int_between_inclusive(-16, 16).unwrap_or(0);
|
||||
let mut at = [pos[0] + dx, pos[1] + 8, pos[2] + dz];
|
||||
if !w.world.loaded(at[0], at[2]) {
|
||||
continue;
|
||||
}
|
||||
// moveToPossibleSpawnPosition
|
||||
let mut above = b.get(at);
|
||||
let mut found = false;
|
||||
for _ in (-8..=8).rev() {
|
||||
at[1] -= 1;
|
||||
let current = b.get(at);
|
||||
if can_spawn_on(&b, at, current, above) {
|
||||
at[1] += 1;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
above = current;
|
||||
}
|
||||
if !found {
|
||||
continue;
|
||||
}
|
||||
// noCollision(getSpawnAABB)
|
||||
let half = f64::from(kind.width as f32 / 2.0);
|
||||
let height = f64::from(kind.height as f32);
|
||||
let (x, y, z) = (
|
||||
f64::from(at[0]) + 0.5,
|
||||
f64::from(at[1]),
|
||||
f64::from(at[2]) + 0.5,
|
||||
);
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(x - half, y, z - half),
|
||||
Vec3::new(x + half, y + height, z + half),
|
||||
);
|
||||
let mut scene = SceneCollisions {
|
||||
world: w.world,
|
||||
binding: w.collision,
|
||||
};
|
||||
if !scene.unobstructed(bounds).unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
// EntityType.create: a random yaw, then Mob.finalizeSpawn.
|
||||
let mut m = host.create_mob(kind.clone(), Vec3::new(x, y, z));
|
||||
let yaw = wrap_degrees(lr.next_float() * 360.0);
|
||||
m.yaw = yaw;
|
||||
m.previous_yaw = yaw;
|
||||
m.head_yaw = yaw;
|
||||
m.body_yaw = yaw;
|
||||
finalize_spawn(&mut m, lr);
|
||||
// Mob.checkSpawnRules (always true for a creaking) and
|
||||
// checkSpawnObstruction (no liquid in the box).
|
||||
if liquid_in(w, m.bounds()) {
|
||||
continue;
|
||||
}
|
||||
let id = m.id;
|
||||
// SpawnUtil: addFreshEntityWithPassengers, then playAmbientSound.
|
||||
let mut events = Vec::new();
|
||||
if !creaking::is_active(&m) {
|
||||
m.voice("entity.creaking.ambient", &mut events);
|
||||
}
|
||||
creaking::set_transient(&mut m, pos);
|
||||
// spawnProtector's caller: the creaking's spawn sound.
|
||||
m.voice("entity.creaking.spawn", &mut events);
|
||||
host.add_mob(m);
|
||||
out.extend(events.into_iter().map(HeartEvent::Mob));
|
||||
out.push(HeartEvent::Sound(
|
||||
"block.creaking_heart.spawn",
|
||||
centre(pos),
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
return Some(id);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `Mob.finalizeSpawn`: the follow range's random spawn bonus and the
|
||||
/// handedness, from the level random.
|
||||
pub fn finalize_spawn(m: &mut Mob, lr: &mut LegacyRandom) {
|
||||
let bonus = lr.triangle(0.0, 0.114_850_000_000_000_01);
|
||||
// ADD_MULTIPLIED_BASE on the base value.
|
||||
m.attrs.follow_range += m.kind.follow_range * bonus;
|
||||
let _left_handed = lr.next_float() < 0.05;
|
||||
}
|
||||
fn wrap_degrees(angle: f32) -> f32 {
|
||||
let mut w = angle % 360.0;
|
||||
if w >= 180.0 {
|
||||
w -= 360.0;
|
||||
}
|
||||
if w < -180.0 {
|
||||
w += 360.0;
|
||||
}
|
||||
w
|
||||
}
|
||||
fn liquid_in(w: &MobWorld, b: Aabb) -> bool {
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) {
|
||||
for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) {
|
||||
for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) {
|
||||
if w.fluid(x, y, z) != crate::blocks::Fluid::None {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `CreakingHeartBlockEntity.serverTick` (hearts that are not uprooted).
|
||||
pub fn server_tick(
|
||||
heart: &mut CreakingHeart,
|
||||
pos: [i32; 3],
|
||||
w: &MobWorld,
|
||||
lr: &mut LegacyRandom,
|
||||
host: &mut impl HeartHost,
|
||||
out: &mut Vec<HeartEvent>,
|
||||
) {
|
||||
heart.ticks_existed += 1;
|
||||
let signal = output_signal(heart, pos, host);
|
||||
if heart.output_signal != signal {
|
||||
heart.output_signal = signal;
|
||||
out.push(HeartEvent::OutputChanged(pos));
|
||||
}
|
||||
if heart.emitter > 0 {
|
||||
if heart.emitter > 50 {
|
||||
emit_particles(heart, pos, 1, true, lr, host, out);
|
||||
emit_particles(heart, pos, 1, false, lr, host, out);
|
||||
}
|
||||
if heart.emitter % 10 == 0 && heart.emitter_target.is_some() {
|
||||
if let Some(m) = protector(heart, host).and_then(|id| host.mob(id)) {
|
||||
heart.emitter_target = Some(m.center());
|
||||
}
|
||||
if let Some(target) = heart.emitter_target {
|
||||
let c = centre(pos);
|
||||
let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0;
|
||||
let sound = [
|
||||
(c[0] - target[0]) * progress + target[0],
|
||||
(c[1] - target[1]) * progress + target[1],
|
||||
(c[2] - target[2]) * progress + target[2],
|
||||
];
|
||||
// playSound(null, BlockPos.containing(soundLocation), ...)
|
||||
let at = centre([
|
||||
sound[0].floor() as i32,
|
||||
sound[1].floor() as i32,
|
||||
sound[2].floor() as i32,
|
||||
]);
|
||||
let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5;
|
||||
out.push(HeartEvent::Sound(
|
||||
"block.creaking_heart.hurt",
|
||||
at,
|
||||
volume,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
}
|
||||
heart.emitter -= 1;
|
||||
}
|
||||
let ticker = heart.ticker;
|
||||
heart.ticker -= 1;
|
||||
if ticker >= 0 {
|
||||
return;
|
||||
}
|
||||
heart.ticker = lr.next_int_bound(5).unwrap_or(0) + 20;
|
||||
let mut b = Blocks {
|
||||
w,
|
||||
changed: Vec::new(),
|
||||
};
|
||||
let state = b.get(pos);
|
||||
// updateCreakingState
|
||||
let active = creaking_active(w);
|
||||
let wanted = if !has_required_logs(&b, state, pos) && heart.creaking.is_none() {
|
||||
"uprooted"
|
||||
} else if active {
|
||||
"awake"
|
||||
} else {
|
||||
"dormant"
|
||||
};
|
||||
let mut updated = state;
|
||||
if b.prop(state, "creaking_heart_state").as_deref() != Some(wanted)
|
||||
&& let Some(next) = b.with_prop(state, "creaking_heart_state", wanted)
|
||||
{
|
||||
updated = next;
|
||||
b.set(pos, next, out);
|
||||
if wanted == "uprooted" {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if heart.creaking.is_none() {
|
||||
let awake = b.prop(updated, "creaking_heart_state").as_deref() == Some("awake");
|
||||
if awake && host.spawning_monsters() {
|
||||
// getNearestPlayer(pos, 32, false): no spectators.
|
||||
let (x, y, z) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
|
||||
let near = w.player.as_ref().is_some_and(|p| {
|
||||
!p.spectator
|
||||
&& (p.position.x - x).powi(2)
|
||||
+ (p.position.y - y).powi(2)
|
||||
+ (p.position.z - z).powi(2)
|
||||
< 32.0 * 32.0
|
||||
});
|
||||
if near && let Some(id) = spawn_protector(pos, w, lr, host, out) {
|
||||
let uuid = host.uuid_for(id);
|
||||
heart.creaking = Some((Some(id), uuid));
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = protector(heart, host) {
|
||||
let persistent = host.mob(id).is_some_and(|m| m.persistent);
|
||||
// playerIsStuckInYou reads the creaking's NEAREST_PLAYERS.
|
||||
let stuck = host.mob_mut(id).is_some_and(|m| {
|
||||
let listed = super::monster_brain::nearest_players(m).contains(&super::Who::Player);
|
||||
let eye = w.player.as_ref().filter(|_| listed).map(|p| p.eye);
|
||||
creaking::player_is_stuck(m, eye)
|
||||
});
|
||||
if !active && !persistent || distance_to_creaking(heart, pos, host) > TOO_FAR || stuck {
|
||||
remove_protector(heart, host, false, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -174,6 +174,13 @@ impl GoalSelector {
|
||||
|
||||
// --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) -------
|
||||
|
||||
/// `Mob.isWithinHome(BlockPos)`.
|
||||
pub fn within_home(c: [i32; 3], r: i32, p: [i32; 3]) -> bool {
|
||||
let d = |i: usize| i64::from(c[i] - p[i]);
|
||||
let r = i64::from(r);
|
||||
d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < r * r
|
||||
}
|
||||
|
||||
impl Mob {
|
||||
/// PathfinderMob.getWalkTargetValue.
|
||||
pub fn walk_target_value(&self, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
@@ -209,17 +216,52 @@ impl Mob {
|
||||
let yt = self.random.next_int_bound(2 * v + 1).unwrap_or(0) - v + fly_height;
|
||||
Some([xt.floor() as i32, yt, zt.floor() as i32])
|
||||
}
|
||||
/// RandomPos.generateRandomPosTowardDirection (no home restriction).
|
||||
fn toward(&mut self, _h: f64, d: [i32; 3]) -> [i32; 3] {
|
||||
/// RandomPos.generateRandomPosTowardDirection: a mob with a home leans
|
||||
/// half the distance back toward it.
|
||||
fn toward(&mut self, h: f64, d: [i32; 3]) -> [i32; 3] {
|
||||
let (mut xt, mut zt) = (f64::from(d[0]), f64::from(d[2]));
|
||||
if let Some((c, _)) = self.ai.home
|
||||
&& h > 1.0
|
||||
{
|
||||
if self.position.x > f64::from(c[0]) {
|
||||
xt -= self.random.next_double() * h / 2.0;
|
||||
} else {
|
||||
xt += self.random.next_double() * h / 2.0;
|
||||
}
|
||||
if self.position.z > f64::from(c[2]) {
|
||||
zt -= self.random.next_double() * h / 2.0;
|
||||
} else {
|
||||
zt += self.random.next_double() * h / 2.0;
|
||||
}
|
||||
}
|
||||
[
|
||||
(f64::from(d[0]) + self.position.x).floor() as i32,
|
||||
(xt + self.position.x).floor() as i32,
|
||||
(f64::from(d[1]) + self.position.y).floor() as i32,
|
||||
(f64::from(d[2]) + self.position.z).floor() as i32,
|
||||
(zt + self.position.z).floor() as i32,
|
||||
]
|
||||
}
|
||||
fn default_check(&self, w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
/// `GoalUtils.isRestricted(mobRestricted(mob, h), mob, pos)`: a mob
|
||||
/// near its home keeps the positions it picks within it.
|
||||
pub fn restricted(&self, h: f64, p: [i32; 3]) -> bool {
|
||||
let Some((c, r)) = self.ai.home else {
|
||||
return false;
|
||||
};
|
||||
let near = {
|
||||
let d = |i: usize, v: f64| f64::from(c[i]) + 0.5 - v;
|
||||
let (x, y, z) = (
|
||||
d(0, self.position.x),
|
||||
d(1, self.position.y),
|
||||
d(2, self.position.z),
|
||||
);
|
||||
let reach = f64::from(r) + h + 1.0;
|
||||
x * x + y * y + z * z < reach * reach
|
||||
};
|
||||
near && !within_home(c, r, p)
|
||||
}
|
||||
fn default_check(&self, w: &MobWorld, h: f64, p: [i32; 3]) -> bool {
|
||||
p[1] >= crate::chunk::MIN_Y
|
||||
&& p[1] < 320
|
||||
&& !self.restricted(h, p)
|
||||
&& self.stable_destination(w, p)
|
||||
&& self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0
|
||||
}
|
||||
@@ -252,7 +294,7 @@ impl Mob {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction(h, v);
|
||||
let p = m.toward(f64::from(h), d);
|
||||
m.default_check(w, p).then_some(p)
|
||||
m.default_check(w, f64::from(h), p).then_some(p)
|
||||
})
|
||||
}
|
||||
/// DefaultRandomPos.getPosAway
|
||||
@@ -275,7 +317,7 @@ impl Mob {
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
m.default_check(w, p).then_some(p)
|
||||
m.default_check(w, f64::from(h), p).then_some(p)
|
||||
})
|
||||
}
|
||||
/// DefaultRandomPos.getPosTowards
|
||||
@@ -291,7 +333,7 @@ impl Mob {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
m.default_check(w, p).then_some(p)
|
||||
m.default_check(w, f64::from(h), p).then_some(p)
|
||||
})
|
||||
}
|
||||
fn land_up_out_of_solid(&self, w: &MobWorld, mut p: [i32; 3]) -> Option<[i32; 3]> {
|
||||
@@ -304,12 +346,64 @@ impl Mob {
|
||||
let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water;
|
||||
(!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
|
||||
}
|
||||
/// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yRotO)`.
|
||||
pub fn view_vector(&self) -> [f64; 3] {
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
let to_rad = std::f32::consts::PI / 180.0;
|
||||
let x = self.previous_head_pitch * to_rad;
|
||||
let y = -self.previous_yaw * to_rad;
|
||||
let (y_cos, y_sin, x_cos, x_sin) = (y.mcos(), y.msin(), x.mcos(), x.msin());
|
||||
[
|
||||
f64::from(y_sin * x_cos),
|
||||
f64::from(-x_sin),
|
||||
f64::from(y_cos * x_cos),
|
||||
]
|
||||
}
|
||||
/// AirAndWaterRandomPos.getPos: within the radians of a direction, kept
|
||||
/// near home, moved up out of solid blocks and free of path maluses.
|
||||
pub fn air_and_water_random_pos(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
h: i32,
|
||||
v: i32,
|
||||
fly_height: i32,
|
||||
xd: f64,
|
||||
zd: f64,
|
||||
) -> Option<[f64; 3]> {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction_within(
|
||||
0.0,
|
||||
f64::from(h),
|
||||
v,
|
||||
fly_height,
|
||||
xd,
|
||||
zd,
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let mut p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) {
|
||||
return None;
|
||||
}
|
||||
// RandomPos.moveUpOutOfSolid
|
||||
if w.solid(p[0], p[1], p[2]) {
|
||||
p[1] += 1;
|
||||
while p[1] <= 319 && w.solid(p[0], p[1], p[2]) {
|
||||
p[1] += 1;
|
||||
}
|
||||
}
|
||||
(m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
|
||||
})
|
||||
}
|
||||
/// LandRandomPos.getPos
|
||||
pub fn land_random_pos(&mut self, w: &MobWorld, h: i32, v: i32) -> Option<[f64; 3]> {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction(h, v);
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) {
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
@@ -371,7 +465,11 @@ impl Mob {
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) {
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
@@ -397,7 +495,11 @@ impl Mob {
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) {
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
@@ -429,7 +531,8 @@ impl Mob {
|
||||
/// creative, within range scaled by visibility, optionally visible.
|
||||
pub fn can_target_player(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
if p.creative {
|
||||
// TargetingConditions.isCombat: never an ally.
|
||||
if p.creative || p.allies.contains(&self.id) {
|
||||
return false;
|
||||
}
|
||||
self.player_in_range(w, range, check_sight)
|
||||
@@ -1337,6 +1440,8 @@ pub struct AvoidEntity {
|
||||
/// Extra condition on the avoider (e.g. untamed cats only).
|
||||
pub when: Option<fn(&Mob) -> bool>,
|
||||
from: Vec3,
|
||||
/// The mob being avoided (`toAvoid`), when it is one.
|
||||
pub found: Option<u32>,
|
||||
}
|
||||
impl AvoidEntity {
|
||||
pub fn new(what: Avoid, max_dist: f32, walk: f64, sprint: f64) -> Self {
|
||||
@@ -1347,6 +1452,7 @@ impl AvoidEntity {
|
||||
sprint,
|
||||
when: None,
|
||||
from: Vec3::ZERO,
|
||||
found: None,
|
||||
}
|
||||
}
|
||||
pub fn when(mut self, f: fn(&Mob) -> bool) -> Self {
|
||||
@@ -1381,11 +1487,16 @@ impl Goal for AvoidEntity {
|
||||
Avoid::Species(list) => {
|
||||
let id = m.id;
|
||||
let y = m.position.y;
|
||||
cx.w.nearby(m.position, max, move |s| {
|
||||
s.id != id && list.contains(&s.species) && (s.position.y - y).abs() <= 3.0 + max
|
||||
})
|
||||
.map(|s| s.position)
|
||||
.next()
|
||||
let hit =
|
||||
cx.w.nearby(m.position, max, move |s| {
|
||||
s.id != id
|
||||
&& list.contains(&s.species)
|
||||
&& (s.position.y - y).abs() <= 3.0 + max
|
||||
})
|
||||
.map(|s| (s.id, s.position))
|
||||
.next();
|
||||
self.found = hit.map(|h| h.0);
|
||||
hit.map(|h| h.1)
|
||||
}
|
||||
};
|
||||
let Some(from) = found else { return false };
|
||||
@@ -1622,11 +1733,23 @@ impl Goal for Breed {
|
||||
);
|
||||
self.love_time += 1;
|
||||
if self.love_time >= reduced(60) && m.distance_sqr(p.position) < 9.0 {
|
||||
// Llama.getBreedOffspring and finalizeSpawnChildFromBreeding's
|
||||
// experience, from the parent's random.
|
||||
let llama = super::llama::is_llama(m.species()).then(|| {
|
||||
let o = super::llama::breed_offspring(m, &p);
|
||||
let xp = 1 + m.random.next_int_bound(7).unwrap_or(0);
|
||||
cx.events.push(MobEvent::Experience {
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
amount: xp as u32,
|
||||
});
|
||||
Box::new(o)
|
||||
});
|
||||
m.extra.in_love = 0;
|
||||
m.extra.age = 6000;
|
||||
cx.events.push(MobEvent::Breed {
|
||||
parent: m.id,
|
||||
partner: p.id,
|
||||
llama,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,9 +142,10 @@ impl Goal for OfferFlower {
|
||||
if !cx.w.daylight || m.random.next_int_bound(8000).unwrap_or(1) != 0 {
|
||||
return false;
|
||||
}
|
||||
// The nearest of #candidate_for_iron_golem_gift: villagers and copper golems.
|
||||
self.villager =
|
||||
cx.w.nearby(m.position, 6.0, |s| {
|
||||
s.species == Species::Villager && s.alive
|
||||
matches!(s.species, Species::Villager | Species::CopperGolem) && s.alive
|
||||
})
|
||||
.map(|s| s.id)
|
||||
.next();
|
||||
@@ -157,8 +158,30 @@ impl Goal for OfferFlower {
|
||||
self.ticks = 400;
|
||||
m.extra.counter = 400;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.extra.counter = 0;
|
||||
// A copper golem the offer ran out beside takes the poppy on its
|
||||
// antenna (#accepts_iron_golem_gift) when it has none.
|
||||
if self.ticks == 0
|
||||
&& let Some(v) = self.villager.and_then(|v| cx.w.seen(v))
|
||||
&& v.species == Species::CopperGolem
|
||||
{
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let (vlo, vhi) = (v.bounds.min_position(), v.bounds.max_position());
|
||||
if lo.x - 6.0 < vhi.x
|
||||
&& hi.x + 6.0 > vlo.x
|
||||
&& lo.y - 2.0 < vhi.y
|
||||
&& hi.y + 2.0 > vlo.y
|
||||
&& lo.z - 6.0 < vhi.z
|
||||
&& hi.z + 6.0 > vlo.z
|
||||
{
|
||||
cx.events.push(MobEvent::Gift {
|
||||
target: v.id,
|
||||
item: "minecraft:poppy",
|
||||
});
|
||||
}
|
||||
}
|
||||
self.villager = None;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
//! ghastling follows players and adults, a harnessed adult can be ridden and
|
||||
//! flown, healing is slow (fast in the rain) and `HappyGhastModel`.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
Mob, MobEvent, MobWorld,
|
||||
anim::{Poses, State},
|
||||
control::{MoveKind, Operation},
|
||||
goals::{Cx, Float, Goal, LOOK, MOVE, Panic, Stroll, Tempt, goal_clone},
|
||||
control::{LookKind, MoveKind, Operation},
|
||||
goals::{Cx, Float, Goal, LOOK, MOVE, goal_clone},
|
||||
nav::NavKind,
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -15,7 +15,7 @@ use horizon_core::{
|
||||
};
|
||||
|
||||
// Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a
|
||||
// baby and 2 as an adult, `home` and `ints[4]` the restriction, `counter`
|
||||
// baby and 2 as an adult, `ai.home` the restriction, `counter`
|
||||
// the end tick of the follow-an-adult range pick.
|
||||
pub const BABY_SCALE: f64 = 0.2375;
|
||||
/// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`).
|
||||
@@ -25,35 +25,41 @@ pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0;
|
||||
pub fn register(m: &mut Mob) {
|
||||
setup(m, m.is_baby());
|
||||
}
|
||||
/// `adultGhastSetup` and `babyGhastSetup`.
|
||||
/// `adultGhastSetup` and `babyGhastSetup`: the ghastling flies with a
|
||||
/// `FlyingMoveControl` and has no goals (its brain drives it); the adult
|
||||
/// floats with `GhastMoveControl` and three goals, its brain stopped.
|
||||
fn setup(m: &mut Mob, baby: bool) {
|
||||
let was = m.extra.scratch[0];
|
||||
m.extra.scratch[0] = if baby { 1 } else { 2 };
|
||||
m.ai.goals.clear();
|
||||
m.ai.nav.stop();
|
||||
// A new move and look control (nothing wanted) and navigation.
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
m.ai.mov.wanted = [0.0; 3];
|
||||
m.ai.mov.speed_modifier = 0.0;
|
||||
m.ai.look.wanted = [0.0; 3];
|
||||
m.ai.look.cooldown = 0;
|
||||
m.extra.counter2 = 0;
|
||||
if baby {
|
||||
m.ai.look.kind = LookKind::Default;
|
||||
m.ai.mov.kind = MoveKind::Flying {
|
||||
max_turn: 180.0,
|
||||
hovers: true,
|
||||
};
|
||||
// BabyFlyingPathNavigation.
|
||||
m.ai.nav.kind = NavKind::Flying;
|
||||
m.ai.nav.can_float = true;
|
||||
m.ai.nav.required_path_length = 48.0;
|
||||
let tempt = m.kind.food.clone();
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(0, Panic::new(2.0));
|
||||
let mut t = Tempt::new(1.25, tempt, false);
|
||||
t.stop_distance = 3.0;
|
||||
g.add(1, t);
|
||||
g.add(2, FollowAdult::default());
|
||||
g.add(4, Stroll::flying(1.0));
|
||||
return;
|
||||
}
|
||||
if was == 1 {
|
||||
super::animal_brain::grown_up(m);
|
||||
}
|
||||
m.ai.mov.kind = MoveKind::Custom;
|
||||
m.ai.nav.kind = NavKind::Ground;
|
||||
m.ai.look.kind = LookKind::HappyGhast;
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(3, Float);
|
||||
g.add(3, HappyGhastFloat);
|
||||
g.add(4, GhastTempt::default());
|
||||
g.add(5, FloatAround { blocks: 16 });
|
||||
}
|
||||
@@ -74,8 +80,10 @@ fn restriction_radius(m: &Mob) -> i32 {
|
||||
}
|
||||
/// `Mob.isWithinHome` for the ghast's restriction.
|
||||
fn within_home(m: &Mob, p: Vec3) -> bool {
|
||||
let Some(h) = m.extra.home else { return true };
|
||||
let r = f64::from(m.extra.ints[4]);
|
||||
let Some((h, r)) = m.ai.home else {
|
||||
return true;
|
||||
};
|
||||
let r = f64::from(r);
|
||||
let (dx, dy, dz) = (
|
||||
f64::from(h[0]) + 0.5 - p.x,
|
||||
f64::from(h[1]) + 0.5 - p.y,
|
||||
@@ -83,58 +91,233 @@ fn within_home(m: &Mob, p: Vec3) -> bool {
|
||||
);
|
||||
dx * dx + dy * dy + dz * dz < r * r
|
||||
}
|
||||
/// `Ghast.GhastMoveControl` with the careful block checks: a push toward
|
||||
/// the wanted point every few ticks while the way is clear.
|
||||
/// `isOnStillTimeout`: a player standing on it (or just off it) holds it
|
||||
/// still (`serverStillTimeout`, kept in `counter`).
|
||||
pub fn on_still_timeout(m: &Mob) -> bool {
|
||||
!m.is_baby() && m.extra.counter > 0
|
||||
}
|
||||
/// `Mob.stopInPlace`.
|
||||
fn stop_in_place(m: &mut Mob) {
|
||||
m.ai.nav.stop();
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.yya = 0.0;
|
||||
m.ai.zza = 0.0;
|
||||
m.ai.speed = 0.0;
|
||||
m.velocity = Vec3::ZERO;
|
||||
}
|
||||
/// `Ghast.GhastMoveControl(careful)`: held still on a still timeout, else
|
||||
/// a push toward the wanted point every 2 to 6 ticks while the way there
|
||||
/// is clear.
|
||||
pub fn move_control(m: &mut Mob, w: &MobWorld) {
|
||||
if on_still_timeout(m) {
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
stop_in_place(m);
|
||||
}
|
||||
if m.ai.mov.operation != Operation::MoveTo {
|
||||
return;
|
||||
}
|
||||
// floatDuration-- <= 0
|
||||
let duration = m.extra.counter2;
|
||||
m.extra.counter2 -= 1;
|
||||
if m.extra.counter2 > 0 {
|
||||
if duration > 0 {
|
||||
return;
|
||||
}
|
||||
m.extra.counter2 += m.random.next_int_bound(5).unwrap_or(0) + 2;
|
||||
let [wx, wy, wz] = m.ai.mov.wanted;
|
||||
let travel = Vec3::new(wx - m.position.x, wy - m.position.y, wz - m.position.z);
|
||||
let len = travel.length();
|
||||
if len < 1.0e-6 {
|
||||
return;
|
||||
}
|
||||
let b = m.bounds();
|
||||
let steps = len.ceil() as i32;
|
||||
let clear = (1..=steps).all(|i| {
|
||||
let f = f64::from(i) / f64::from(steps);
|
||||
let d = Vec3::new(travel.x * f, travel.y * f, travel.z * f);
|
||||
let at = Aabb::new(
|
||||
b.min_position().add_vector(d),
|
||||
b.max_position().add_vector(d),
|
||||
);
|
||||
w.no_collision(at) && !touches_fluid(w, at)
|
||||
});
|
||||
if clear {
|
||||
let speed = AIR_SPEED;
|
||||
m.velocity = m.velocity.add_vector(Vec3::new(
|
||||
travel.x / len * f64::from(speed),
|
||||
travel.y / len * f64::from(speed),
|
||||
travel.z / len * f64::from(speed),
|
||||
));
|
||||
if can_reach(m, w, travel) {
|
||||
// travel.normalize().scale(FLYING_SPEED * 5 / 3)
|
||||
let len = (travel.x * travel.x + travel.y * travel.y + travel.z * travel.z).sqrt();
|
||||
let unit = if len < f64::from(1.0e-5_f32) {
|
||||
Vec3::ZERO
|
||||
} else {
|
||||
Vec3::new(travel.x / len, travel.y / len, travel.z / len)
|
||||
};
|
||||
let speed = FLYING_SPEED * 5.0 / 3.0;
|
||||
m.velocity =
|
||||
m.velocity
|
||||
.add_vector(Vec3::new(unit.x * speed, unit.y * speed, unit.z * speed));
|
||||
} else {
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
}
|
||||
}
|
||||
/// A careful ghast does not float into water or lava.
|
||||
fn touches_fluid(w: &MobWorld, b: Aabb) -> bool {
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
/// `EntityDimensions.makeBoundingBox` at another position.
|
||||
fn bounds_at(m: &Mob, p: Vec3) -> Aabb {
|
||||
let half = f64::from(m.width()) / 2.0;
|
||||
let h = f64::from(m.height());
|
||||
Aabb::new(
|
||||
Vec3::new(p.x - half, p.y, p.z - half),
|
||||
Vec3::new(p.x + half, p.y + h, p.z + half),
|
||||
)
|
||||
}
|
||||
/// `GhastMoveControl.canReach`: every block around the destination box can
|
||||
/// be crossed, and so can every block the box sweeps through on the way.
|
||||
fn can_reach(m: &Mob, w: &MobWorld, travel: Vec3) -> bool {
|
||||
let aabb = m.bounds();
|
||||
let dest = aabb.move_by(travel);
|
||||
let around = dest.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||
let (lo, hi) = (around.min_position(), around.max_position());
|
||||
for x in lo.x.floor() as i32..=hi.x.floor() as i32 {
|
||||
for y in lo.y.floor() as i32..=hi.y.floor() as i32 {
|
||||
for z in lo.z.floor() as i32..=hi.z.floor() as i32 {
|
||||
if w.fluid(x, y, z) != crate::blocks::Fluid::None {
|
||||
return true;
|
||||
if !traversal_possible(m, w, None, [x, y, z], false, false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
let (water, lava) = (m.fluids.in_water, m.fluids.in_lava);
|
||||
let start = m.position;
|
||||
let end = start.add_vector(travel);
|
||||
horizon_core::geometry::sweep_intersected_blocks(start, end, dest, 1 << 22, |p, _| {
|
||||
let at = [p.x, p.y, p.z];
|
||||
let unit = Aabb::new(
|
||||
Vec3::new(f64::from(at[0]), f64::from(at[1]), f64::from(at[2])),
|
||||
Vec3::new(
|
||||
f64::from(at[0]) + 1.0,
|
||||
f64::from(at[1]) + 1.0,
|
||||
f64::from(at[2]) + 1.0,
|
||||
),
|
||||
);
|
||||
aabb.intersects(unit) || traversal_possible(m, w, Some((start, end)), at, water, lava)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
/// `GhastMoveControl.blockTraversalPossible` for a careful ghast: air, or no
|
||||
/// collision (along the way when `along` is given), never a
|
||||
/// `#happy_ghast_avoids` block, and a fluid only where the ghast already is.
|
||||
fn traversal_possible(
|
||||
m: &Mob,
|
||||
w: &MobWorld,
|
||||
along: Option<(Vec3, Vec3)>,
|
||||
p: [i32; 3],
|
||||
through_water: bool,
|
||||
through_lava: bool,
|
||||
) -> bool {
|
||||
let state = w.world.block(p[0], p[1], p[2]);
|
||||
if w.facts.is_air(state) {
|
||||
return true;
|
||||
}
|
||||
let boxes = w.block_collision_boxes(p[0], p[1], p[2]);
|
||||
let no_collisions = match along {
|
||||
Some((from, to)) => !bounds_at(m, from).collided_along_vector(to.subtract(from), &boxes),
|
||||
None => boxes.is_empty(),
|
||||
};
|
||||
if w.has_tag(
|
||||
"minecraft:happy_ghast_avoids",
|
||||
w.block_name(p[0], p[1], p[2]),
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let (fluid, height) = w.fluid_height(p[0], p[1], p[2]);
|
||||
if fluid != crate::blocks::Fluid::None {
|
||||
let collided = match along {
|
||||
None => true,
|
||||
// collidedWithFluid: the fluid's own height.
|
||||
Some((from, to)) => {
|
||||
let fluid_box = Aabb::new(
|
||||
Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])),
|
||||
Vec3::new(
|
||||
f64::from(p[0]) + 1.0,
|
||||
f64::from(p[1]) + height,
|
||||
f64::from(p[2]) + 1.0,
|
||||
),
|
||||
);
|
||||
bounds_at(m, from).collided_along_vector(to.subtract(from), &[fluid_box])
|
||||
}
|
||||
};
|
||||
if collided {
|
||||
return match fluid {
|
||||
crate::blocks::Fluid::Water => through_water,
|
||||
_ => through_lava,
|
||||
};
|
||||
}
|
||||
}
|
||||
no_collisions
|
||||
}
|
||||
/// `HappyGhast.HappyGhastLookControl`: square to the world on a still
|
||||
/// timeout, face what it looks at, else face its motion
|
||||
/// (`Ghast.faceMovementDirection`).
|
||||
pub fn look_control(m: &mut Mob) {
|
||||
use horizon_core::geometry::trig;
|
||||
let to_deg = 180.0_f32 / std::f32::consts::PI;
|
||||
if on_still_timeout(m) {
|
||||
// Mth.wrapDegrees90
|
||||
let mut close = m.yaw % 90.0;
|
||||
if close >= 45.0 {
|
||||
close -= 90.0;
|
||||
}
|
||||
if close < -45.0 {
|
||||
close += 90.0;
|
||||
}
|
||||
m.yaw -= close;
|
||||
m.head_yaw = m.yaw;
|
||||
} else if m.ai.look.cooldown > 0 {
|
||||
m.ai.look.cooldown -= 1;
|
||||
let [wx, _, wz] = m.ai.look.wanted;
|
||||
m.yaw = -(trig::atan2(wx - m.position.x, wz - m.position.z) as f32) * to_deg;
|
||||
m.body_yaw = m.yaw;
|
||||
m.head_yaw = m.body_yaw;
|
||||
} else if m.ai.target.is_none() {
|
||||
let v = m.velocity;
|
||||
m.yaw = -(trig::atan2(v.x, v.z) as f32) * to_deg;
|
||||
m.body_yaw = m.yaw;
|
||||
}
|
||||
}
|
||||
/// `HappyGhast.tick`'s still timeout: it runs out (after the first three
|
||||
/// seconds) unless a player stands on top (`scanPlayerAboveGhast`).
|
||||
pub fn still_tick(m: &mut Mob, w: &MobWorld) {
|
||||
if m.is_baby() {
|
||||
m.extra.counter = 0;
|
||||
return;
|
||||
}
|
||||
if m.extra.counter > 0 && m.age > 60 {
|
||||
m.extra.counter -= 1;
|
||||
}
|
||||
if player_above(m, w) {
|
||||
m.extra.counter = 10;
|
||||
}
|
||||
}
|
||||
/// `scanPlayerAboveGhast`: a player (not one riding a happy ghast) within
|
||||
/// a block around the top, up to half the ghast's height above it.
|
||||
pub fn player_above(m: &Mob, w: &MobWorld) -> bool {
|
||||
let Some(p) = w.player.as_ref().filter(|p| !p.spectator) else {
|
||||
return false;
|
||||
};
|
||||
if m.rider.is_some() {
|
||||
return false;
|
||||
}
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let area = Aabb::new(
|
||||
Vec3::new(lo.x - 1.0, hi.y - f64::from(1.0e-5_f32), lo.z - 1.0),
|
||||
Vec3::new(hi.x + 1.0, hi.y + (hi.y - lo.y) / 2.0, hi.z + 1.0),
|
||||
);
|
||||
area.contains(p.position)
|
||||
}
|
||||
/// `HappyGhastFloatGoal`: a `FloatGoal` off a still timeout.
|
||||
#[derive(Clone, Debug)]
|
||||
struct HappyGhastFloat;
|
||||
impl Goal for HappyGhastFloat {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"HappyGhastFloatGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
Float.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
!on_still_timeout(m) && Float.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
Float.can_use(m, cx)
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
Float.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// `TemptGoal.ForNonPathfinders`: drift toward a player holding food, or
|
||||
/// food and harnesses for a bare adult.
|
||||
@@ -151,6 +334,9 @@ impl GhastTempt {
|
||||
}
|
||||
impl Goal for GhastTempt {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"ForNonPathfinders"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
@@ -160,22 +346,24 @@ impl Goal for GhastTempt {
|
||||
return false;
|
||||
}
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
// Attributes.TEMPT_RANGE 16.
|
||||
// getNearestPlayer(TargetingConditions.forNonCombat()
|
||||
// .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too.
|
||||
let visibility = if p.sneaking { 0.8 } else { 1.0 };
|
||||
let range = (16.0_f64 * visibility).max(2.0);
|
||||
p.alive
|
||||
&& !p.creative
|
||||
&& !p.spectator
|
||||
&& (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand))
|
||||
&& m.distance_sqr(p.position) <= 256.0
|
||||
&& m.distance_sqr(p.position) <= range * range
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
// stopNavigation: setWait; calmDown = reducedTickDelay(100).
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
self.calm_down = 50;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
self.calm_down = super::goals::reduced(100);
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(p) = cx.w.player.clone() else { return };
|
||||
m.look_at(p.eye);
|
||||
// stopDistance 7.
|
||||
if m.distance_sqr(p.position) < 49.0 {
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
} else {
|
||||
@@ -227,6 +415,9 @@ impl FloatAround {
|
||||
}
|
||||
impl Goal for FloatAround {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"RandomFloatAroundGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
@@ -242,85 +433,39 @@ impl Goal for FloatAround {
|
||||
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
false
|
||||
}
|
||||
/// `getSuitableFlyToPosition`: the first of 64 random points within 16
|
||||
/// blocks (and home) that is good; failing that, the last point, kept
|
||||
/// below the motion-blocking surface.
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let c = m.position;
|
||||
let mut result: Option<Vec3> = None;
|
||||
for _ in 0..64 {
|
||||
let r = &mut m.random;
|
||||
let t = Vec3::new(
|
||||
c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
);
|
||||
result = Some(t);
|
||||
if within_home(m, t) && self.good(cx.w, t) {
|
||||
break;
|
||||
}
|
||||
result = None;
|
||||
}
|
||||
let mut t = result.unwrap_or_else(|| {
|
||||
let choose = |m: &mut Mob| {
|
||||
let r = &mut m.random;
|
||||
Vec3::new(
|
||||
c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.x + f64::from((r.next_float() * 2.0 - 1.0) * 16.0),
|
||||
c.y + f64::from((r.next_float() * 2.0 - 1.0) * 16.0),
|
||||
c.z + f64::from((r.next_float() * 2.0 - 1.0) * 16.0),
|
||||
)
|
||||
});
|
||||
};
|
||||
let mut result: Option<Vec3> = None;
|
||||
for _ in 0..64 {
|
||||
let t = choose(m);
|
||||
result = within_home(m, t).then_some(t);
|
||||
if let Some(t) = result
|
||||
&& self.good(cx.w, t)
|
||||
{
|
||||
m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mut t = result.unwrap_or_else(|| choose(m));
|
||||
let top =
|
||||
cx.w.motion_blocking_height(t.x.floor() as i32, t.z.floor() as i32);
|
||||
if top < t.y.floor() as i32 && top > crate::chunk::MIN_Y {
|
||||
t.y = c.y - (c.y - t.y).abs();
|
||||
t.y = m.position.y - (m.position.y - t.y).abs();
|
||||
}
|
||||
m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0);
|
||||
}
|
||||
}
|
||||
/// `BabyFollowAdult`: a ghastling drifts toward the nearest player or adult
|
||||
/// until it is a few blocks away.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct FollowAdult {
|
||||
close: f64,
|
||||
}
|
||||
impl FollowAdult {
|
||||
fn target(m: &Mob, cx: &Cx) -> Option<Vec3> {
|
||||
let player =
|
||||
cx.w.player
|
||||
.as_ref()
|
||||
.filter(|p| p.alive && !p.spectator && m.distance_sqr(p.position) <= 32.0 * 32.0)
|
||||
.map(|p| p.position);
|
||||
player.or_else(|| {
|
||||
cx.w.nearby(m.position, 32.0, |s| {
|
||||
s.species == Species::HappyGhast && !s.baby
|
||||
})
|
||||
.next()
|
||||
.map(|s| s.position)
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Goal for FollowAdult {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
m.is_baby()
|
||||
&& Self::target(m, cx).is_some_and(|t| {
|
||||
let close = if self.close > 0.0 { self.close } else { 16.0 };
|
||||
m.position.distance_squared(t) > close * close
|
||||
})
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
Self::target(m, cx).is_some_and(|t| m.position.distance_squared(t) > 9.0)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
// UniformInt.of(3, 16).
|
||||
self.close = f64::from(3 + m.random.next_int_bound(14).unwrap_or(0));
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(t) = Self::target(m, cx) {
|
||||
m.nav_move_to(cx.w, [t.x, t.y, t.z], 1.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// What a rider asks (`getRiddenInput`, `tickRidden`).
|
||||
pub fn ridden(m: &mut Mob) {
|
||||
let Some(r) = m.rider else { return };
|
||||
@@ -351,13 +496,17 @@ pub fn ridden(m: &mut Mob) {
|
||||
m.ai.zza = forward * scale;
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
}
|
||||
/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby
|
||||
/// setup at the age boundary, the home, face-the-motion and slow healing.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
/// The adult or ghastling setup for its age (`ageBoundaryReached`).
|
||||
pub fn ensure_setup(m: &mut Mob) {
|
||||
let baby = m.is_baby();
|
||||
if m.extra.scratch[0] != if baby { 1 } else { 2 } {
|
||||
setup(m, baby);
|
||||
}
|
||||
}
|
||||
/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby
|
||||
/// setup at the age boundary, the home, face-the-motion and slow healing.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
ensure_setup(m);
|
||||
// checkRestriction.
|
||||
if m.extra.leash.is_none() && m.rider.is_none() {
|
||||
let radius = restriction_radius(m);
|
||||
@@ -366,26 +515,17 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
let stale = match m.extra.home {
|
||||
Some(h) => {
|
||||
// !hasHome || !home.closerThan(blockPosition, radius + 16) || radius changed
|
||||
let stale = match m.ai.home {
|
||||
Some((h, r)) => {
|
||||
(h[0] - here[0]).pow(2) + (h[1] - here[1]).pow(2) + (h[2] - here[2]).pow(2)
|
||||
>= (radius + 16).pow(2)
|
||||
|| radius != m.extra.ints[4]
|
||||
|| radius != r
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if stale {
|
||||
m.extra.home = Some(here);
|
||||
m.extra.ints[4] = radius;
|
||||
}
|
||||
}
|
||||
// LookControl: face where it is going.
|
||||
if !baby && m.rider.is_none() {
|
||||
let v = m.velocity;
|
||||
if m.ai.target.is_none() && v.x * v.x + v.z * v.z > 1.0e-6 {
|
||||
m.yaw = -(v.x.atan2(v.z) as f32).to_degrees();
|
||||
m.body_yaw = m.yaw;
|
||||
m.head_yaw = m.yaw;
|
||||
m.ai.home = Some((here, radius));
|
||||
}
|
||||
}
|
||||
// continuousHeal: a point every 30 seconds, every second in rain.
|
||||
@@ -401,6 +541,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
m.health = (m.health + 1.0).min(m.attrs.max_health);
|
||||
}
|
||||
}
|
||||
still_tick(m, w);
|
||||
}
|
||||
/// Sounds: the ghastling has its own.
|
||||
pub fn sounds(m: &Mob) -> [&'static str; 3] {
|
||||
|
||||
@@ -209,6 +209,21 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
return;
|
||||
};
|
||||
// PathfinderMob.whenLeashedTo: home is the holder's block, within the
|
||||
// elastic distance less one.
|
||||
let elastic = if m.species() == super::Species::HappyGhast {
|
||||
10.0
|
||||
} else {
|
||||
ELASTIC
|
||||
};
|
||||
m.ai.home = Some((
|
||||
[
|
||||
state.position.x.floor() as i32,
|
||||
state.position.y.floor() as i32,
|
||||
state.position.z.floor() as i32,
|
||||
],
|
||||
elastic as i32 - 1,
|
||||
));
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let center = Vec3::new(
|
||||
@@ -265,6 +280,14 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
};
|
||||
m.extra.leash_spin *= friction;
|
||||
}
|
||||
/// The lead comes off (`Mob.onLeashRemoved`): no more home.
|
||||
pub fn remove(m: &mut Mob) -> Option<Holder> {
|
||||
let was = m.extra.leash.take();
|
||||
if was.is_some() {
|
||||
m.ai.home = None;
|
||||
}
|
||||
was
|
||||
}
|
||||
/// `PathfinderMob.closeRangeLeashBehaviour`: walk to within two blocks of
|
||||
/// the holder unless panicking.
|
||||
fn close_range(m: &mut Mob, w: &MobWorld, holder: &HolderState) {
|
||||
|
||||
@@ -116,6 +116,22 @@ impl MobWorld<'_> {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `BlockState.getCollisionShape(level, pos)` (the empty collision
|
||||
/// context) as boxes in the world.
|
||||
pub fn block_collision_boxes(&self, x: i32, y: i32, z: i32) -> Vec<Aabb> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let state = self.world.block(x, y, z);
|
||||
let at = horizon_core::position::BlockPos::new(x, y, z);
|
||||
let context = horizon_world::collision_context::CollisionContext::empty(false);
|
||||
let offset = Vec3::new(f64::from(x), f64::from(y), f64::from(z));
|
||||
self.collision
|
||||
.collision_shape_with_context(&mut scene, state, at, &context)
|
||||
.map(|shape| shape.boxes().iter().map(|b| b.move_by(offset)).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub fn no_collision(&self, b: Aabb) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
@@ -125,6 +141,38 @@ impl MobWorld<'_> {
|
||||
}
|
||||
}
|
||||
impl Mob {
|
||||
/// `Entity.refreshDimensions` after growing from `old_w` by `old_h`:
|
||||
/// `fudgePositionAfterSizeChange` moves the mob to the free spot nearest
|
||||
/// its old centre where the bigger box fits (`findFreePosition`), or
|
||||
/// failing that, one that fits at the old height.
|
||||
pub fn fudge_position_after_size_change(&mut self, w: &MobWorld, old_w: f64, old_h: f64) {
|
||||
let (new_w, new_h, _) = self.dims();
|
||||
let small = new_w <= 4.0 && new_h <= 4.0;
|
||||
if self.age == 0 || self.no_physics() || !small || !(new_w > old_w || new_h > old_h) {
|
||||
return;
|
||||
}
|
||||
let center = Vec3::new(
|
||||
self.position.x,
|
||||
self.position.y + old_h / 2.0,
|
||||
self.position.z,
|
||||
);
|
||||
let dw = (new_w - old_w).max(0.0) + 1.0e-6;
|
||||
let dh = (new_h - old_h).max(0.0) + 1.0e-6;
|
||||
let at = |allowed: Aabb, size_y: f64| free_position(w, allowed, center, new_w, size_y);
|
||||
if let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, dh, dw)), new_h) {
|
||||
self.position = Vec3::new(p.x, p.y - new_h / 2.0, p.z);
|
||||
return;
|
||||
}
|
||||
if new_w > old_w
|
||||
&& new_h > old_h
|
||||
&& let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, 1.0e-6, dw)), old_h)
|
||||
{
|
||||
self.position = Vec3::new(p.x, p.y - old_h / 2.0 + 1.0e-6, p.z);
|
||||
}
|
||||
}
|
||||
fn no_physics(&self) -> bool {
|
||||
false
|
||||
}
|
||||
pub fn eye_y(&self) -> f64 {
|
||||
self.position.y + self.eye_height()
|
||||
}
|
||||
@@ -249,13 +297,12 @@ impl Mob {
|
||||
let x_hit = differs(wanted.x, moved.x);
|
||||
let z_hit = differs(wanted.z, moved.z);
|
||||
self.horizontal_collision = x_hit || z_hit;
|
||||
// A server's mobs are authoritative (`isLocalInstanceAuthoritative`):
|
||||
// the vertical flags update even without vertical movement.
|
||||
let moved_vertically = wanted.y.abs() > 0.0;
|
||||
let mut vertical = false;
|
||||
if moved_vertically {
|
||||
vertical = wanted.y != moved.y;
|
||||
self.vertical_collision_below = vertical && wanted.y < 0.0;
|
||||
self.on_ground = self.vertical_collision_below;
|
||||
}
|
||||
let vertical = wanted.y != moved.y;
|
||||
self.vertical_collision_below = vertical && wanted.y < 0.0;
|
||||
self.on_ground = self.vertical_collision_below;
|
||||
// LivingEntity.checkFallDamage refreshes the fluid state out of water
|
||||
// (touching water resets the fall).
|
||||
if !self.fluids.in_water {
|
||||
@@ -359,6 +406,11 @@ impl Mob {
|
||||
]
|
||||
}
|
||||
fn cause_fall_damage(&mut self, events: &mut Vec<MobEvent>) {
|
||||
// Breeze.causeFallDamage: a landing from higher than three blocks.
|
||||
if self.species() == super::Species::Breeze && self.fall_distance > 3.0 {
|
||||
let at = [self.position.x, self.position.y, self.position.z];
|
||||
events.push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0));
|
||||
}
|
||||
if self.kind.flags.fall_immune {
|
||||
return;
|
||||
}
|
||||
@@ -391,7 +443,7 @@ impl Mob {
|
||||
0.02
|
||||
}
|
||||
/// Entity.getGravity: none while isNoGravity.
|
||||
fn gravity(&self) -> f64 {
|
||||
pub fn gravity(&self) -> f64 {
|
||||
if self.no_gravity {
|
||||
0.0
|
||||
} else {
|
||||
@@ -413,14 +465,21 @@ impl Mob {
|
||||
self.travel_in_air(w, input, events);
|
||||
}
|
||||
}
|
||||
/// LivingEntity.travelFlying (ghast 0.02, phantom 0.2): no gravity, 0.91 drag.
|
||||
/// LivingEntity.travelFlying: no gravity, `0.91F` drag in the air,
|
||||
/// `0.8F` in water and 0.5 in lava. A happy ghast swims as fast as it
|
||||
/// flies (`HappyGhast.travel`); the others at 0.02.
|
||||
fn travel_flying(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
let (speed, drag) = if self.fluids.in_water {
|
||||
(0.02, 0.8)
|
||||
} else if self.fluids.in_lava {
|
||||
(0.02, 0.5)
|
||||
let fluid_speed = if self.species() == super::Species::HappyGhast {
|
||||
self.kind.air_speed
|
||||
} else {
|
||||
(self.kind.air_speed, 0.91)
|
||||
0.02
|
||||
};
|
||||
let (speed, drag) = if self.fluids.in_water {
|
||||
(fluid_speed, f64::from(0.8_f32))
|
||||
} else if self.fluids.in_lava {
|
||||
(fluid_speed, 0.5)
|
||||
} else {
|
||||
(self.kind.air_speed, f64::from(0.91_f32))
|
||||
};
|
||||
self.move_relative(speed, input);
|
||||
self.do_move(w, events);
|
||||
@@ -634,3 +693,44 @@ fn fluid_falling(gravity: f64, falling: bool, m: Vec3) -> Vec3 {
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// `CollisionGetter.findFreePosition`: within `allowed`, the point nearest
|
||||
/// `preferred` at which a box of the size, centred there, meets no block.
|
||||
fn free_position(
|
||||
w: &MobWorld,
|
||||
allowed: Aabb,
|
||||
preferred: Vec3,
|
||||
size_x: f64,
|
||||
size_y: f64,
|
||||
) -> Option<Vec3> {
|
||||
use horizon_core::geometry::{ShapeOp, VoxelShape};
|
||||
let allowed_shape = VoxelShape::from_box(allowed).ok()?;
|
||||
if allowed_shape.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let half = Vec3::new(size_x / 2.0, size_y / 2.0, size_x / 2.0);
|
||||
let area = allowed.inflate(half);
|
||||
let (lo, hi) = (area.min_position(), area.max_position());
|
||||
let mut collisions = VoxelShape::empty();
|
||||
// getBlockCollisions: the block shapes that reach into the area.
|
||||
for x in (lo.x - 1.0e-7).floor() as i32 - 1..=(hi.x + 1.0e-7).floor() as i32 + 1 {
|
||||
for y in (lo.y - 1.0e-7).floor() as i32 - 1..=(hi.y + 1.0e-7).floor() as i32 + 1 {
|
||||
for z in (lo.z - 1.0e-7).floor() as i32 - 1..=(hi.z + 1.0e-7).floor() as i32 + 1 {
|
||||
let boxes = w.block_collision_boxes(x, y, z);
|
||||
let touches = boxes.iter().any(|b| {
|
||||
let (a, c) = (b.min_position(), b.max_position());
|
||||
a.x < hi.x && c.x > lo.x && a.y < hi.y && c.y > lo.y && a.z < hi.z && c.z > lo.z
|
||||
});
|
||||
if !touches {
|
||||
continue;
|
||||
}
|
||||
for b in boxes {
|
||||
let grown = VoxelShape::from_box(b.inflate(half)).ok()?;
|
||||
collisions = collisions.join(&grown, ShapeOp::OR).ok()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let free = allowed_shape.join(&collisions, ShapeOp::ONLY_FIRST).ok()?;
|
||||
free.closest_point(preferred)
|
||||
}
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
//! spit ranged attack, hunting wolves (and, for traders, zombies and
|
||||
//! illagers) and `LlamaModel`.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Seen, Species, Who,
|
||||
anim::{Poses, State},
|
||||
equine,
|
||||
Mob, MobEvent, MobWorld, Seen, Species, Who, equine,
|
||||
goals::{
|
||||
Breed, Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Panic,
|
||||
Prey, RandomLookAround, Stroll, Tempt, goal_clone,
|
||||
@@ -14,7 +12,6 @@ use super::{
|
||||
};
|
||||
use crate::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
pub const VARIANTS: [&str; 4] = ["creamy", "white", "brown", "gray"];
|
||||
/// `Llama.getMaxTemper`.
|
||||
@@ -29,9 +26,10 @@ pub fn is_llama(s: Species) -> bool {
|
||||
pub fn is_trader(m: &Mob) -> bool {
|
||||
m.species() == Species::TraderLlama
|
||||
}
|
||||
/// `Llama.getStrength`.
|
||||
/// `Llama.getStrength`: the stored strength (0 for a llama that was never
|
||||
/// given one; `setStrength` keeps it within 1 to 5).
|
||||
pub fn strength(m: &Mob) -> i32 {
|
||||
i32::from(m.extra.variant2).clamp(1, 5)
|
||||
i32::from(m.extra.variant2)
|
||||
}
|
||||
/// `getInventoryColumns`: a chest holds three rows of `strength` columns.
|
||||
pub fn inventory_columns(m: &Mob) -> i32 {
|
||||
@@ -64,7 +62,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(1, Panic::new(2.0));
|
||||
}
|
||||
g.add(1, equine::RunAroundLikeCrazy);
|
||||
g.add(2, super::caravan::FollowCaravan::new(2.1));
|
||||
g.add(2, super::caravan::FollowCaravan::new(f64::from(2.1_f32)));
|
||||
g.add(3, RangedAttack::new(1.25, 40, 40, 20.0, spit));
|
||||
g.add(3, Panic::new(1.2));
|
||||
g.add(4, Breed::new(1.0));
|
||||
@@ -129,6 +127,59 @@ pub fn offspring(child: &mut Mob, a: &Mob, b: &Mob, r: &mut impl RandomSource) {
|
||||
child.persistent = true;
|
||||
}
|
||||
}
|
||||
/// A llama's baby as `Llama.getBreedOffspring` makes it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Offspring {
|
||||
pub max_health: f32,
|
||||
pub jump: f64,
|
||||
pub speed: f64,
|
||||
pub strength: u8,
|
||||
pub variant: u8,
|
||||
}
|
||||
/// `Llama.getBreedOffspring` with `AbstractHorse.setOffspringAttributes`,
|
||||
/// drawn from the parent's random with the partner's stock.
|
||||
pub fn breed_offspring(m: &mut Mob, partner: &Seen) -> Offspring {
|
||||
// Seen.profession is the partner's strength.
|
||||
let top = strength(m).max(i32::from(partner.profession));
|
||||
let (health, jump, speed, own) = (
|
||||
f64::from(m.attrs.max_health),
|
||||
m.extra.vector[0],
|
||||
m.attrs.speed,
|
||||
m.extra.variant,
|
||||
);
|
||||
let r = &mut m.random;
|
||||
let max_health = equine::offspring(health, partner.stats[0], 15.0, 30.0, r) as f32;
|
||||
let jump = equine::offspring(jump, partner.stats[1], 0.4, 1.0, r);
|
||||
let speed = equine::offspring(speed, partner.stats[2], 0.1125, 0.3375, r);
|
||||
let mut s = r.next_int_bound(top).unwrap_or(0) + 1;
|
||||
if r.next_float() < 0.03 {
|
||||
s += 1;
|
||||
}
|
||||
let variant = if r.next_boolean() {
|
||||
own
|
||||
} else {
|
||||
partner.variant
|
||||
};
|
||||
Offspring {
|
||||
max_health,
|
||||
jump,
|
||||
speed,
|
||||
strength: s.clamp(1, 5) as u8,
|
||||
variant,
|
||||
}
|
||||
}
|
||||
/// The game makes the baby drawn by `breed_offspring`.
|
||||
pub fn apply_offspring(child: &mut Mob, o: &Offspring) {
|
||||
child.attrs.max_health = o.max_health;
|
||||
child.health = o.max_health;
|
||||
child.extra.vector[0] = o.jump;
|
||||
child.attrs.speed = o.speed;
|
||||
child.extra.variant2 = o.strength;
|
||||
child.extra.variant = o.variant;
|
||||
if is_trader(child) {
|
||||
child.persistent = true;
|
||||
}
|
||||
}
|
||||
/// `LlamaHurtByTargetGoal`: stops hunting right after a spit.
|
||||
#[derive(Clone, Debug)]
|
||||
struct LlamaHurtBy(HurtByTarget);
|
||||
@@ -255,17 +306,6 @@ pub fn decor(m: &Mob) -> Option<(String, String)> {
|
||||
(model.into(), format!("entity/equipment/llama_body/{name}"))
|
||||
})
|
||||
}
|
||||
/// `LlamaModel.setupAnim`.
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
super::anim::quadruped(p, s);
|
||||
let chest = m.extra.chested && !s.baby;
|
||||
for part in ["right_chest", "left_chest"] {
|
||||
if !chest {
|
||||
p.visible(part, false);
|
||||
}
|
||||
}
|
||||
let _ = PI;
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -42,6 +42,31 @@ pub struct State {
|
||||
pub homes: Option<std::sync::Arc<Vec<[i32; 3]>>>,
|
||||
/// A ravager carrying a raider, set every tick from `Extra::rider`.
|
||||
pub rider: bool,
|
||||
/// The raid counts this raider (`addWaveMob` ran since it joined or was
|
||||
/// loaded with its `RaidId`).
|
||||
pub registered: bool,
|
||||
/// `Raider.hurtServer` updates the raid's bar before the damage lands:
|
||||
/// when it was last hurt (see [`next_hurt_seq`]) and its health then.
|
||||
pub hurt_seq: u64,
|
||||
pub pre_hurt_health: f32,
|
||||
}
|
||||
|
||||
static HURT_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
/// A counter ordering the hurts of raiders across the game.
|
||||
pub fn next_hurt_seq() -> u64 {
|
||||
HURT_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
|
||||
}
|
||||
/// `Raider.hurtServer`: a raider in an active raid asks its raid to update
|
||||
/// the bar with the health it has before this hit.
|
||||
pub fn note_hurt(m: &mut Mob) {
|
||||
let health = m.health;
|
||||
if let Some(s) = m.extra.raider.as_deref_mut()
|
||||
&& s.raid_id.is_some()
|
||||
&& s.active_raid
|
||||
{
|
||||
s.hurt_seq = next_hurt_seq();
|
||||
s.pre_hurt_health = health;
|
||||
}
|
||||
}
|
||||
impl State {
|
||||
/// A ravager carrying a raider (`hasControllingPassenger`).
|
||||
|
||||
@@ -292,6 +292,8 @@ pub fn body(m: &Mob) -> (String, String) {
|
||||
)
|
||||
}
|
||||
}
|
||||
// CopperGolemOxidationLevels: the texture of the weathering.
|
||||
S::CopperGolem => (m.kind.model_key(), super::copper_golem::texture(m)),
|
||||
_ => (m.kind.model_key(), m.kind.texture.clone()),
|
||||
}
|
||||
}
|
||||
@@ -510,6 +512,11 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
|
||||
white,
|
||||
true,
|
||||
),
|
||||
// The copper golem's eyes glow (LivingEntityEmissiveLayer, eyes render type).
|
||||
S::CopperGolem => {
|
||||
let eyes = super::copper_golem::eye_texture(m);
|
||||
push(&mut v, "copper_golem#eyes", &eyes, white, true);
|
||||
}
|
||||
S::Spider | S::CaveSpider => push(
|
||||
&mut v,
|
||||
&m.kind.model_key(),
|
||||
|
||||
@@ -3,13 +3,10 @@
|
||||
//! digging up a seed, the explored positions, laying eggs when bred, and
|
||||
//! `SnifferModel`'s keyframe animations.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld,
|
||||
Mob, MobEvent,
|
||||
anim::{Poses, State},
|
||||
brain::{Sink, Ttl, WalkTarget, duration},
|
||||
goals::{Breed, Cx, Float, Goal, Panic, Tempt, goal_clone},
|
||||
keyframes::Animation,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// Sniffer state: `variant` the state (below), `scratch[0]` the state the
|
||||
@@ -24,15 +21,14 @@ pub const SEARCHING: u8 = 4;
|
||||
pub const DIGGING: u8 = 5;
|
||||
pub const RISING: u8 = 6;
|
||||
|
||||
const SNIFF_COOLDOWN: i32 = 9600;
|
||||
/// `Sniffer.getBabyStartAge`.
|
||||
pub const BABY_START_AGE: i32 = -48000;
|
||||
|
||||
pub fn state(m: &Mob) -> u8 {
|
||||
m.extra.variant
|
||||
}
|
||||
fn set_state(m: &mut Mob, s: u8) {
|
||||
m.extra.variant = s;
|
||||
fn now(m: &Mob) -> i32 {
|
||||
m.age as i32
|
||||
}
|
||||
/// `Sniffer.getDefaultDimensions`: lower while digging.
|
||||
pub fn digging(m: &Mob) -> bool {
|
||||
@@ -44,468 +40,36 @@ pub fn register(m: &mut Mob) {
|
||||
m.set_malus(PathType::Water, -1.0);
|
||||
m.set_malus(PathType::OnTopOfPowderSnow, -1.0);
|
||||
m.set_malus(PathType::DamageCautious, -1.0);
|
||||
let tempt = m.kind.tempt.clone();
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(0, SnifferPanic(Panic::new(2.0)));
|
||||
g.add(
|
||||
0,
|
||||
Brain {
|
||||
walk: None,
|
||||
sink: Sink::new(500, 700),
|
||||
look: None,
|
||||
look_until: 0,
|
||||
digging: false,
|
||||
happy: false,
|
||||
cooldown: Ttl::default(),
|
||||
sniff_target: None,
|
||||
run: Run::None,
|
||||
until: 0,
|
||||
breed: Breed::new(1.0),
|
||||
tempt: Tempt::new(1.25, tempt, false),
|
||||
love_on: false,
|
||||
tempt_on: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
/// The core's `AnimalPanic`, forgetting any sniffing when it starts.
|
||||
#[derive(Clone, Debug)]
|
||||
struct SnifferPanic(Panic);
|
||||
impl Goal for SnifferPanic {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
self.0.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
set_state(m, IDLING);
|
||||
self.0.start(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Run {
|
||||
None,
|
||||
Digging,
|
||||
FinishedDigging,
|
||||
Searching,
|
||||
Happy,
|
||||
Scenting,
|
||||
Sniffing,
|
||||
DoNothing,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct Brain {
|
||||
walk: Option<WalkTarget>,
|
||||
sink: Sink,
|
||||
/// `LOOK_TARGET` and the end of `LookAtTargetSink`'s run (0 when not running).
|
||||
look: Option<[f64; 3]>,
|
||||
look_until: i32,
|
||||
/// `SNIFFER_DIGGING`, `SNIFFER_HAPPY`, `SNIFF_COOLDOWN`, `SNIFFER_SNIFFING_TARGET`.
|
||||
digging: bool,
|
||||
happy: bool,
|
||||
cooldown: Ttl,
|
||||
sniff_target: Option<[i32; 3]>,
|
||||
/// The timed behaviour running and when it times out.
|
||||
run: Run,
|
||||
until: i32,
|
||||
breed: Breed,
|
||||
tempt: Tempt,
|
||||
love_on: bool,
|
||||
tempt_on: bool,
|
||||
}
|
||||
impl Goal for Brain {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
true
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.brain(m, cx);
|
||||
}
|
||||
}
|
||||
fn now(m: &Mob) -> i32 {
|
||||
m.age as i32
|
||||
}
|
||||
fn sound(m: &Mob, cx: &mut Cx, name: &'static str, pitch: f32) {
|
||||
cx.events
|
||||
.push(MobEvent::Sound(name, m.center(), 1.0, pitch));
|
||||
/// `Sniffer.setState`.
|
||||
pub fn set_state(m: &mut Mob, s: u8) {
|
||||
m.extra.variant = s;
|
||||
}
|
||||
/// `Sniffer.getOnPos`: the block under its feet.
|
||||
fn on_pos(m: &Mob) -> [i32; 3] {
|
||||
pub fn on_pos(m: &Mob) -> [i32; 3] {
|
||||
[
|
||||
m.position.x.floor() as i32,
|
||||
(m.position.y - 0.2).floor() as i32,
|
||||
(m.position.y - f64::from(0.2_f32)).floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
]
|
||||
}
|
||||
/// `Sniffer.getHeadBlock`: 2.25 blocks ahead of it, a little above its feet.
|
||||
/// `Sniffer.getHeadBlock`: 2.25 blocks along `getForward()`, at its feet
|
||||
/// plus 0.2.
|
||||
pub fn head_block(m: &Mob) -> [i32; 3] {
|
||||
let (yaw, pitch) = (m.yaw.to_radians(), m.head_pitch.to_radians());
|
||||
let forward = [
|
||||
f64::from(-yaw.sin() * pitch.cos()),
|
||||
f64::from(-pitch.sin()),
|
||||
f64::from(yaw.cos() * pitch.cos()),
|
||||
];
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
// Vec3.directionFromRotation(xRot, yRot).
|
||||
let to_rad = std::f32::consts::PI / 180.0;
|
||||
let y = -m.yaw * to_rad - std::f32::consts::PI;
|
||||
let x = -m.head_pitch * to_rad;
|
||||
let (y_cos, y_sin) = (y.mcos(), y.msin());
|
||||
let x_cos = -x.mcos();
|
||||
let forward = [f64::from(y_sin * x_cos), f64::from(y_cos * x_cos)];
|
||||
[
|
||||
(m.position.x + forward[0] * 2.25).floor() as i32,
|
||||
(m.position.y + f64::from(0.2_f32)).floor() as i32,
|
||||
(m.position.z + forward[2] * 2.25).floor() as i32,
|
||||
(m.position.z + forward[1] * 2.25).floor() as i32,
|
||||
]
|
||||
}
|
||||
impl Brain {
|
||||
fn tempted(&self) -> bool {
|
||||
self.tempt_on
|
||||
}
|
||||
/// `Sniffer.canSniff`.
|
||||
fn can_sniff(&self, m: &Mob) -> bool {
|
||||
!self.tempted()
|
||||
&& !m.ai.panicking
|
||||
&& !m.fluids.in_water
|
||||
&& m.extra.in_love <= 0
|
||||
&& m.on_ground
|
||||
&& m.rider.is_none()
|
||||
&& m.extra.leash.is_none()
|
||||
}
|
||||
/// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable.
|
||||
fn can_dig_at(&self, m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
w.has_tag(
|
||||
"minecraft:sniffer_diggable_block",
|
||||
w.block_name(p[0], p[1], p[2]),
|
||||
) && !m.extra.positions.contains(&p)
|
||||
&& m.create_path_to(w, p, 1).is_some_and(|path| path.reached)
|
||||
}
|
||||
/// `Sniffer.canDig`.
|
||||
fn can_dig(&self, m: &mut Mob, w: &MobWorld) -> bool {
|
||||
if m.ai.panicking
|
||||
|| self.tempted()
|
||||
|| m.is_baby()
|
||||
|| m.fluids.in_water
|
||||
|| !m.on_ground
|
||||
|| m.rider.is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let head = head_block(m);
|
||||
self.can_dig_at(m, w, [head[0], head[1] - 1, head[2]])
|
||||
}
|
||||
/// `Sniffer.calculateDigPosition`.
|
||||
fn dig_position(&self, m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> {
|
||||
for idx in 0..5 {
|
||||
let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else {
|
||||
continue;
|
||||
};
|
||||
let below = [
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32 - 1,
|
||||
p[2].floor() as i32,
|
||||
];
|
||||
if self.can_dig_at(m, w, below) {
|
||||
return Some(below);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn transition(&mut self, m: &mut Mob, cx: &mut Cx, to: u8) {
|
||||
match to {
|
||||
FEELING_HAPPY => sound(m, cx, "entity.sniffer.happy", 1.0),
|
||||
SCENTING => {
|
||||
let pitch = if m.is_baby() { 1.3 } else { 1.0 };
|
||||
sound(m, cx, "entity.sniffer.scenting", pitch)
|
||||
}
|
||||
SNIFFING => sound(m, cx, "entity.sniffer.sniffing", 1.0),
|
||||
DIGGING => m.extra.ints[3] = now(m) + 120,
|
||||
RISING => sound(m, cx, "entity.sniffer.digging_stop", 1.0),
|
||||
_ => {}
|
||||
}
|
||||
set_state(m, to);
|
||||
}
|
||||
/// `SnifferAi.resetSniffing`.
|
||||
fn reset_sniffing(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.digging = false;
|
||||
self.sniff_target = None;
|
||||
self.transition(m, cx, IDLING);
|
||||
}
|
||||
fn brain(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.cooldown.tick();
|
||||
// Tempted: the tempting player memory while the goal runs.
|
||||
if m.ai.panicking {
|
||||
self.walk = None;
|
||||
self.sink.stop(m, &mut self.walk);
|
||||
self.love_on = false;
|
||||
self.tempt_on = false;
|
||||
} else {
|
||||
self.start_behaviours(m, cx);
|
||||
}
|
||||
self.sink.tick(m, cx, &mut self.walk);
|
||||
self.tick_running(m, cx);
|
||||
}
|
||||
/// `Brain.startEachNonRunningBehavior` for the first valid activity.
|
||||
fn start_behaviours(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let n = now(m);
|
||||
// DIG, SNIFF, IDLE.
|
||||
let dig = self.digging && self.walk.is_none();
|
||||
let sniff = self.sniff_target.is_some() && self.walk.is_some();
|
||||
if dig {
|
||||
if self.run == Run::None && !self.cooldown.present() && self.can_sniff(m) {
|
||||
self.run = Run::Digging;
|
||||
self.until = n + duration(m, 160, 180);
|
||||
self.transition(m, cx, DIGGING);
|
||||
}
|
||||
if self.run == Run::None && self.cooldown.present() {
|
||||
self.run = Run::FinishedDigging;
|
||||
self.until = n + 40;
|
||||
self.transition(m, cx, RISING);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if sniff {
|
||||
if self.run == Run::None && self.can_sniff(m) {
|
||||
self.run = Run::Searching;
|
||||
self.until = n + 600;
|
||||
self.transition(m, cx, SEARCHING);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.digging {
|
||||
return;
|
||||
}
|
||||
// IDLE: love, tempt, look at the target, feeling happy, one of the rest.
|
||||
if !self.love_on && !self.tempt_on && self.breed.can_use(m, cx) {
|
||||
self.reset_sniffing(m, cx);
|
||||
self.breed.start(m, cx);
|
||||
self.love_on = true;
|
||||
}
|
||||
if !self.love_on && !self.tempt_on && self.tempt.can_use(m, cx) {
|
||||
self.reset_sniffing(m, cx);
|
||||
self.tempt.start(m, cx);
|
||||
self.tempt_on = true;
|
||||
}
|
||||
if self.look.is_some() && self.look_until == 0 {
|
||||
self.look_until = n + duration(m, 45, 90);
|
||||
}
|
||||
if self.run == Run::None && self.happy {
|
||||
self.run = Run::Happy;
|
||||
self.until = n + duration(m, 40, 100);
|
||||
self.transition(m, cx, FEELING_HAPPY);
|
||||
}
|
||||
if self.run == Run::None {
|
||||
self.run_one(m, cx);
|
||||
}
|
||||
}
|
||||
/// The idle `RunOne`: a weighted random pick among what can start.
|
||||
fn run_one(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let n = now(m);
|
||||
// (weight, option)
|
||||
let mut options: Vec<(i32, u8)> = Vec::new();
|
||||
if self.look.is_some() && self.walk.is_none() {
|
||||
options.push((2, 0));
|
||||
}
|
||||
if !self.happy && !self.love_on && !self.tempted() && self.sniff_target.is_none() {
|
||||
options.push((1, 1));
|
||||
}
|
||||
if self.walk.is_none()
|
||||
&& self.sniff_target.is_none()
|
||||
&& !self.cooldown.present()
|
||||
&& !m.is_baby()
|
||||
&& self.can_sniff(m)
|
||||
{
|
||||
options.push((1, 2));
|
||||
}
|
||||
if cx.w.player.as_ref().is_some_and(|p| {
|
||||
p.alive && !p.creative && m.distance_sqr(p.position) <= 36.0 && !p.spectator
|
||||
}) {
|
||||
options.push((1, 3));
|
||||
}
|
||||
if self.walk.is_none() {
|
||||
options.push((1, 4));
|
||||
}
|
||||
options.push((2, 5));
|
||||
let total: i32 = options.iter().map(|o| o.0).sum();
|
||||
// A weighted pick from the high bits (`WeightedList.getRandom`).
|
||||
let mut roll = ((m.random.next_float() * total as f32) as i32).min(total - 1);
|
||||
let mut pick = options[0].1;
|
||||
for (w, o) in &options {
|
||||
if roll < *w {
|
||||
pick = *o;
|
||||
break;
|
||||
}
|
||||
roll -= w;
|
||||
}
|
||||
match pick {
|
||||
// SetWalkTargetFromLookTarget(1.0, 3).
|
||||
0 => {
|
||||
if let Some(l) = self.look {
|
||||
self.walk = Some(WalkTarget::new(
|
||||
[
|
||||
l[0].floor() as i32,
|
||||
l[1].floor() as i32,
|
||||
l[2].floor() as i32,
|
||||
],
|
||||
1.0,
|
||||
3,
|
||||
));
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
self.run = Run::Scenting;
|
||||
self.until = n + duration(m, 40, 80);
|
||||
self.transition(m, cx, SCENTING);
|
||||
}
|
||||
2 => {
|
||||
self.run = Run::Sniffing;
|
||||
self.until = n + duration(m, 40, 80);
|
||||
self.transition(m, cx, SNIFFING);
|
||||
}
|
||||
// SetEntityLookTarget(PLAYER, 6).
|
||||
3 => {
|
||||
if let Some(p) = &cx.w.player {
|
||||
self.look = Some(p.eye);
|
||||
self.look_until = 0;
|
||||
}
|
||||
}
|
||||
// RandomStroll.stroll(1.0).
|
||||
4 => {
|
||||
if let Some(p) = m.land_random_pos(cx.w, 10, 7) {
|
||||
self.walk = Some(WalkTarget::new(
|
||||
[
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
],
|
||||
1.0,
|
||||
0,
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.run = Run::DoNothing;
|
||||
self.until = n + duration(m, 5, 20);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Brain.tickRunningBehaviors`.
|
||||
fn tick_running(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let n = now(m);
|
||||
let timed_out = n > self.until;
|
||||
// The delegated idle behaviours.
|
||||
if self.love_on {
|
||||
if self.breed.can_continue(m, cx) {
|
||||
self.breed.tick(m, cx);
|
||||
} else {
|
||||
self.breed.stop(m, cx);
|
||||
self.love_on = false;
|
||||
}
|
||||
}
|
||||
if self.tempt_on {
|
||||
self.tempt.stop_distance = if m.is_baby() { 2.5 } else { 3.5 };
|
||||
if self.tempt.can_continue(m, cx) {
|
||||
self.tempt.tick(m, cx);
|
||||
} else {
|
||||
self.tempt.stop(m, cx);
|
||||
self.tempt_on = false;
|
||||
}
|
||||
}
|
||||
// LookAtTargetSink.
|
||||
if self.look_until != 0 {
|
||||
if let Some(l) = self.look
|
||||
&& n <= self.look_until
|
||||
{
|
||||
m.look_at(l);
|
||||
} else {
|
||||
self.look = None;
|
||||
self.look_until = 0;
|
||||
}
|
||||
}
|
||||
match self.run {
|
||||
Run::None => {}
|
||||
Run::Digging => {
|
||||
let ok = self.digging && self.can_dig(m, cx.w) && m.extra.in_love <= 0;
|
||||
if timed_out || !ok {
|
||||
if timed_out {
|
||||
self.cooldown.set(SNIFF_COOLDOWN);
|
||||
} else {
|
||||
self.reset_sniffing(m, cx);
|
||||
}
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::FinishedDigging => {
|
||||
if timed_out || !self.digging {
|
||||
self.transition(m, cx, IDLING);
|
||||
// onDiggingComplete: remember the spot when it finished.
|
||||
if timed_out {
|
||||
let p = on_pos(m);
|
||||
m.extra.positions.insert(0, p);
|
||||
m.extra.positions.truncate(21);
|
||||
}
|
||||
self.digging = false;
|
||||
self.happy = true;
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Searching => {
|
||||
let still = if !self.can_sniff(m) {
|
||||
self.transition(m, cx, IDLING);
|
||||
false
|
||||
} else {
|
||||
match (self.walk, self.sniff_target) {
|
||||
(Some(w), Some(t)) => w.pos == t,
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
if timed_out || !still {
|
||||
if self.can_dig(m, cx.w) && self.can_sniff(m) {
|
||||
self.digging = true;
|
||||
}
|
||||
self.sink.stop(m, &mut self.walk);
|
||||
self.sniff_target = None;
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Happy => {
|
||||
if timed_out {
|
||||
self.transition(m, cx, IDLING);
|
||||
self.happy = false;
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Scenting => {
|
||||
if timed_out {
|
||||
self.transition(m, cx, IDLING);
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Sniffing => {
|
||||
if timed_out || !self.can_sniff(m) {
|
||||
self.transition(m, cx, IDLING);
|
||||
if timed_out && let Some(p) = self.dig_position(m, cx.w) {
|
||||
self.sniff_target = Some(p);
|
||||
self.walk = Some(WalkTarget::new(p, 1.25, 0));
|
||||
}
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::DoNothing => {
|
||||
if timed_out {
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Sniffer.tick` and `Sniffer.aiStep` additions: the animation states,
|
||||
/// the dropped seed and the water malus.
|
||||
pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
@@ -540,14 +104,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
if current == SEARCHING && m.age.is_multiple_of(20) {
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.sniffer.searching",
|
||||
m.center(),
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
// The searching sound is the client's (`playSearchingSound`).
|
||||
// onPathfindingStart / Done: water only blocks the way while it is dry.
|
||||
let wet = m.fluids.in_water || m.fire_ticks > 0;
|
||||
m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 });
|
||||
|
||||
@@ -45,6 +45,7 @@ pub enum Species {
|
||||
WanderingTrader,
|
||||
IronGolem,
|
||||
SnowGolem,
|
||||
CopperGolem,
|
||||
Zombie,
|
||||
Husk,
|
||||
Drowned,
|
||||
@@ -642,6 +643,16 @@ pub const ALL: &[Def] = &[
|
||||
None,
|
||||
Baby::None
|
||||
),
|
||||
def!(
|
||||
CopperGolem,
|
||||
"copper_golem",
|
||||
"copper_golem#main",
|
||||
"entity/copper_golem/copper_golem",
|
||||
A::CopperGolem,
|
||||
["", "entity.copper_golem.hurt", "entity.copper_golem.death"],
|
||||
Some("entity.copper_golem.step"),
|
||||
Baby::None
|
||||
),
|
||||
def!(
|
||||
Zombie,
|
||||
"zombie",
|
||||
@@ -1428,6 +1439,7 @@ impl Def {
|
||||
| S::MagmaCube
|
||||
| S::Wither
|
||||
| S::Allay
|
||||
| S::Breeze
|
||||
),
|
||||
flying: matches!(s, S::Ghast | S::Phantom | S::HappyGhast),
|
||||
climber: matches!(s, S::Spider | S::CaveSpider),
|
||||
@@ -1481,7 +1493,7 @@ impl Def {
|
||||
&& !aquatic
|
||||
&& !matches!(
|
||||
s,
|
||||
S::Villager | S::WanderingTrader | S::IronGolem | S::SnowGolem
|
||||
S::Villager | S::WanderingTrader | S::IronGolem | S::SnowGolem | S::CopperGolem
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -1526,6 +1538,8 @@ impl Def {
|
||||
| S::Ravager
|
||||
| S::Wither
|
||||
| S::Warden
|
||||
| S::Breeze
|
||||
| S::Creaking
|
||||
)
|
||||
}
|
||||
/// The item tag Animal.isFood tests.
|
||||
@@ -1632,7 +1646,8 @@ impl Def {
|
||||
| S::Dolphin
|
||||
| S::Axolotl
|
||||
| S::IronGolem
|
||||
| S::SnowGolem => 120,
|
||||
| S::SnowGolem
|
||||
| S::CopperGolem => 120,
|
||||
_ if self.flags(false).animal => 120,
|
||||
_ => 80,
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(1, Float);
|
||||
g.add(1, TamePanic(Panic::new(1.5)));
|
||||
g.add(2, SitWhenOrdered);
|
||||
g.add(3, AvoidLlamas);
|
||||
g.add(3, AvoidLlamas::new());
|
||||
g.add(4, LeapAtTarget::new(0.4));
|
||||
g.add(5, MeleeAttack::new(1.0, true));
|
||||
g.add(6, FollowOwner::new(1.0, 10.0, 2.0));
|
||||
@@ -255,38 +255,56 @@ impl Goal for SitWhenOrdered {
|
||||
}
|
||||
/// `Wolf.WolfAvoidEntityGoal`: untamed wolves flee llamas.
|
||||
#[derive(Clone, Debug)]
|
||||
struct AvoidLlamas;
|
||||
struct AvoidLlamas(super::goals::AvoidEntity);
|
||||
impl AvoidLlamas {
|
||||
fn new() -> Self {
|
||||
Self(super::goals::AvoidEntity::new(
|
||||
super::goals::Avoid::Species(vec![Species::Llama, Species::TraderLlama]),
|
||||
24.0,
|
||||
1.5,
|
||||
1.5,
|
||||
))
|
||||
}
|
||||
}
|
||||
/// `Wolf.WolfAvoidEntityGoal`: a wild wolf runs from a llama, the more
|
||||
/// likely the stronger it is (`strength >= random.nextInt(5)`), and drops
|
||||
/// its target while it does.
|
||||
impl Goal for AvoidLlamas {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"WolfAvoidEntityGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
self.0.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.extra.tame {
|
||||
if !self.0.can_use(m, cx) {
|
||||
return false;
|
||||
}
|
||||
let pos = m.position;
|
||||
let llama =
|
||||
cx.w.nearby(pos, 24.0, |s| {
|
||||
matches!(s.species, Species::Llama | Species::TraderLlama) && s.alive
|
||||
})
|
||||
.map(|s| s.position)
|
||||
.next();
|
||||
let Some(from) = llama else {
|
||||
// Seen.profession is the llama's strength (`variant2`).
|
||||
let Some(strength) = self
|
||||
.0
|
||||
.found
|
||||
.and_then(|id| cx.w.seen(id))
|
||||
.map(|s| s.profession)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// DefaultRandomPos.getPosAway(16, 7, from).
|
||||
let away = Vec3::new(pos.x - from.x, 0.0, pos.z - from.z);
|
||||
let len = (away.x * away.x + away.z * away.z).sqrt().max(1e-6);
|
||||
let target = [
|
||||
pos.x + away.x / len * 16.0,
|
||||
pos.y,
|
||||
pos.z + away.z / len * 16.0,
|
||||
];
|
||||
m.nav_move_to(cx.w, target, 1.5)
|
||||
!m.extra.tame && i32::from(strength) >= m.random.next_int_bound(5).unwrap_or(0)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
!m.ai.nav.is_done()
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.ai.target = None;
|
||||
self.0.start(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx)
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.ai.target = None;
|
||||
self.0.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// `FollowOwnerGoal(speed, startDistance, stopDistance)`.
|
||||
|
||||
@@ -212,19 +212,26 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
|
||||
// ---- Raids: the raid activities and the gift for a hero.
|
||||
|
||||
/// No raid where the villager stands (`ServerLevel.getRaidAt` is null).
|
||||
pub const RAID_NONE: u8 = 0;
|
||||
/// A raid is near but no wave is on (`Activity.PRE_RAID`).
|
||||
/// A raid is near, before or between its waves.
|
||||
pub const PRE_RAID: u8 = 1;
|
||||
/// A wave is on (`Activity.RAID`).
|
||||
/// A raid is near and a wave is on.
|
||||
pub const RAID: u8 = 2;
|
||||
/// The raid was won: the villagers celebrate.
|
||||
/// The raid there was won: the villagers celebrate.
|
||||
pub const RAID_VICTORY: u8 = 3;
|
||||
/// The raid there was lost (still found by `getRaidAt` until it stops).
|
||||
pub const RAID_LOSS: u8 = 4;
|
||||
|
||||
/// Villager state beyond `Extra`'s scratch fields.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ext {
|
||||
/// Which raid package the villager follows.
|
||||
/// The raid `getRaidAt` finds where the villager stands (`RAID_NONE`
|
||||
/// ... `RAID_LOSS`), set by the game every tick.
|
||||
pub raid: u8,
|
||||
/// That raid has spawned a wave and is not between waves
|
||||
/// (`hasFirstWaveSpawned && !isBetweenWaves`).
|
||||
pub raid_wave: bool,
|
||||
/// What the villager remembers of players (`gossips`).
|
||||
pub gossips: crate::gossip::Gossips,
|
||||
pub last_gossip_time: i64,
|
||||
@@ -250,7 +257,7 @@ pub fn ext(m: &Mob) -> Option<&Ext> {
|
||||
pub fn ext_mut(m: &mut Mob) -> &mut Ext {
|
||||
m.extra.villager.get_or_insert_with(Box::default)
|
||||
}
|
||||
/// The raid package the villager follows (`RAID_NONE` ... `RAID_VICTORY`).
|
||||
/// The raid where the villager stands (`RAID_NONE` ... `RAID_LOSS`).
|
||||
pub fn raid_status(m: &Mob) -> u8 {
|
||||
ext(m).map_or(RAID_NONE, |e| e.raid)
|
||||
}
|
||||
@@ -258,14 +265,15 @@ pub fn raid_status(m: &Mob) -> u8 {
|
||||
pub fn raid_nearby(m: &Mob) -> bool {
|
||||
ext(m).is_some_and(|e| e.raid != RAID_NONE)
|
||||
}
|
||||
/// The raid near the villager: `Some(true)` while a wave is on
|
||||
/// `ResetRaidStatus`: no raid, a stopped one or a lost one.
|
||||
pub fn raid_over_or_lost(m: &Mob) -> bool {
|
||||
matches!(raid_status(m), RAID_NONE | RAID_LOSS)
|
||||
}
|
||||
/// `SetRaidStatus`: `Some(true)` while a wave is on
|
||||
/// (`hasFirstWaveSpawned && !isBetweenWaves`), `Some(false)` otherwise.
|
||||
pub fn raid_state(m: &Mob) -> Option<bool> {
|
||||
match ext(m).map_or(RAID_NONE, |e| e.raid) {
|
||||
RAID_NONE => None,
|
||||
RAID => Some(true),
|
||||
_ => Some(false),
|
||||
}
|
||||
let e = ext(m)?;
|
||||
(e.raid != RAID_NONE).then_some(e.raid_wave)
|
||||
}
|
||||
/// `Villager.getVillagerXp`.
|
||||
pub fn xp(m: &Mob) -> i32 {
|
||||
|
||||
@@ -19,13 +19,13 @@ use horizon_core::{
|
||||
};
|
||||
|
||||
/// `MemorySlot.NEVER_EXPIRE`.
|
||||
const NEVER: i64 = i64::MAX;
|
||||
pub(super) const NEVER: i64 = i64::MAX;
|
||||
|
||||
/// `MemorySlot`: a value and its time to live.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Slot<T> {
|
||||
v: Option<T>,
|
||||
ttl: i64,
|
||||
pub(super) ttl: i64,
|
||||
}
|
||||
impl<T> Default for Slot<T> {
|
||||
fn default() -> Self {
|
||||
@@ -36,7 +36,8 @@ impl<T> Default for Slot<T> {
|
||||
}
|
||||
}
|
||||
impl<T> Slot<T> {
|
||||
fn tick(&mut self) {
|
||||
/// `MemorySlot.tick`.
|
||||
pub(super) fn tick(&mut self) {
|
||||
if self.v.is_some() && self.ttl != NEVER {
|
||||
if self.ttl <= 0 {
|
||||
self.clear();
|
||||
@@ -66,6 +67,9 @@ impl<T> Slot<T> {
|
||||
pub fn get(&self) -> Option<&T> {
|
||||
self.v.as_ref()
|
||||
}
|
||||
pub fn get_mut(&mut self) -> Option<&mut T> {
|
||||
self.v.as_mut()
|
||||
}
|
||||
pub fn present(&self) -> bool {
|
||||
self.v.is_some()
|
||||
}
|
||||
@@ -77,7 +81,7 @@ impl<T: Clone> Slot<T> {
|
||||
}
|
||||
impl<T> Slot<Vec<T>> {
|
||||
/// `Brain.setMemory` of a collection: an empty one erases the memory.
|
||||
fn set_list(&mut self, v: Vec<T>) {
|
||||
pub(super) fn set_list(&mut self, v: Vec<T>) {
|
||||
if v.is_empty() {
|
||||
self.clear();
|
||||
} else {
|
||||
@@ -137,7 +141,7 @@ pub struct WalkTarget {
|
||||
pub close: i32,
|
||||
}
|
||||
impl WalkTarget {
|
||||
fn block(p: [i32; 3], speed: f32, close: i32) -> Self {
|
||||
pub(super) fn block(p: [i32; 3], speed: f32, close: i32) -> Self {
|
||||
Self {
|
||||
target: Tracker::Block(p),
|
||||
speed,
|
||||
@@ -145,7 +149,7 @@ impl WalkTarget {
|
||||
}
|
||||
}
|
||||
/// `new WalkTarget(Vec3, ...)`: the block containing the point.
|
||||
fn point(p: [f64; 3], speed: f32, close: i32) -> Self {
|
||||
pub(super) fn point(p: [f64; 3], speed: f32, close: i32) -> Self {
|
||||
Self::block(
|
||||
[
|
||||
p[0].floor() as i32,
|
||||
@@ -162,8 +166,8 @@ impl WalkTarget {
|
||||
/// cache of `Sensor.isEntityTargetable`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Visible {
|
||||
list: Vec<Who>,
|
||||
cache: Vec<(Who, bool)>,
|
||||
pub(super) list: Vec<Who>,
|
||||
pub(super) cache: Vec<(Who, bool)>,
|
||||
}
|
||||
|
||||
/// The memories a villager's brain registers.
|
||||
@@ -2514,7 +2518,7 @@ impl B {
|
||||
if cx.lr.next_int_bound(20).unwrap_or(0) != 0 {
|
||||
return false;
|
||||
}
|
||||
if !super::villager::raid_nearby(m) {
|
||||
if super::villager::raid_over_or_lost(m) {
|
||||
let b = brain_mut(m);
|
||||
b.default_activity = Act::Idle;
|
||||
b.update_from_schedule(cx.w.game_time, cx.w.day_time);
|
||||
|
||||
@@ -39,15 +39,15 @@ pub const DARKNESS_DURATION: i32 = 260;
|
||||
pub const DARKNESS_REAPPLY: i32 = 200;
|
||||
|
||||
// AnimState keyframe slots.
|
||||
const ROAR: usize = 0;
|
||||
const SNIFF: usize = 1;
|
||||
const EMERGE: usize = 2;
|
||||
const DIGGING: usize = 3;
|
||||
const ATTACK: usize = 4;
|
||||
const SONIC_BOOM: usize = 5;
|
||||
pub const ROAR: usize = 0;
|
||||
pub const SNIFF: usize = 1;
|
||||
pub const EMERGE: usize = 2;
|
||||
pub const DIGGING: usize = 3;
|
||||
pub const ATTACK: usize = 4;
|
||||
pub const SONIC_BOOM: usize = 5;
|
||||
// AnimState values: tendril and heart animation (ticks, 10 at the start).
|
||||
const TENDRIL: usize = 0;
|
||||
const HEART: usize = 1;
|
||||
pub const TENDRIL: usize = 0;
|
||||
pub const HEART: usize = 1;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Pose {
|
||||
@@ -392,6 +392,19 @@ pub fn register(m: &mut Mob) {
|
||||
w.sensor_timer = phase;
|
||||
}
|
||||
}
|
||||
/// `Sensor.randomlyDelayStart` for the warden's sensors, in brain order
|
||||
/// (`NEAREST_PLAYERS`, then `WARDEN_ENTITY_SENSOR`, which sets the phase of
|
||||
/// the combined scan here).
|
||||
pub fn delay_sensors(m: &mut Mob) {
|
||||
if m.species() != Species::Warden {
|
||||
return;
|
||||
}
|
||||
let _players = m.random.next_int_bound(20).unwrap_or(0);
|
||||
let entities = m.random.next_int_bound(20).unwrap_or(0);
|
||||
if let Some(w) = m.extra.warden.as_mut() {
|
||||
w.sensor_timer = entities;
|
||||
}
|
||||
}
|
||||
/// `Warden.finalizeSpawn`: a minute until it digs back down; a summoned
|
||||
/// warden climbs out of the ground first.
|
||||
pub fn finalize(m: &mut Mob, triggered: bool, events: &mut Vec<MobEvent>) {
|
||||
|
||||
@@ -79,6 +79,58 @@ impl MobWorld<'_> {
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
}
|
||||
/// Level.clip with VISUAL shapes and no fluids: true on a miss. Glass
|
||||
/// (`TransparentBlock`) and bars and panes (`IronBarsBlock`) have no
|
||||
/// visual shape; mud, soul sand and powder snow look like full blocks.
|
||||
pub fn visual_clear_between(&self, from: Vec3, to: Vec3) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let full = horizon_core::geometry::Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if self.facts.is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let name = self.facts.get(state).name.trim_start_matches("minecraft:");
|
||||
if name.ends_with("glass") || name.ends_with("glass_pane") || name.ends_with("_bars") {
|
||||
return None;
|
||||
}
|
||||
if matches!(name, "mud" | "soul_sand" | "powder_snow") {
|
||||
return full
|
||||
.move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))
|
||||
.clip(from, to)
|
||||
.map(|_| ());
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|_| ())
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
}
|
||||
/// Level.clip with COLLIDER shapes and no fluids: where the segment
|
||||
/// first hits a block, if it does.
|
||||
pub fn clip_block(&self, from: Vec3, to: Vec3) -> Option<Vec3> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if self.facts.is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|hit| hit.location)
|
||||
});
|
||||
result.ok().flatten()
|
||||
}
|
||||
/// LivingEntity.hasLineOfSight: eye to eye within 128 blocks.
|
||||
pub fn line_of_sight(&self, from_eye: Vec3, to: Vec3) -> bool {
|
||||
let d =
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
//! `PatrolSpawner`: every ten to eleven minutes of daylight, one time in five,
|
||||
//! a pillager patrol gathers 24 to 47 blocks from a random player who is not
|
||||
//! near a village. The level is read through [`PatrolLevel`] and the pillagers
|
||||
//! are made by the caller, so the game and the differential test
|
||||
//! (`tools/test_raid_parity.py`) run the same decisions and random draws.
|
||||
use crate::mobs::{
|
||||
Species,
|
||||
spawn_rules::{self, Reason, SpawnLevel},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
/// What the patrol spawner reads from the level.
|
||||
pub trait PatrolLevel: SpawnLevel {
|
||||
/// The `spawn_patrols` game rule.
|
||||
fn spawn_patrols(&self) -> bool;
|
||||
/// `Level.isBrightOutside`: no fixed time and a sky darkening below 4.
|
||||
fn bright_outside(&self) -> bool;
|
||||
/// The level's players, in `level.players()` order: block position and
|
||||
/// whether the player is a spectator.
|
||||
fn patrol_players(&self) -> Vec<([i32; 3], bool)>;
|
||||
/// `ServerLevel.sectionsToVillage` (`PoiManager`): 0 to 7.
|
||||
fn sections_to_village(&self, pos: [i32; 3]) -> i32;
|
||||
/// The chunk at chunk coordinates is loaded (`hasChunk`).
|
||||
fn has_chunk(&self, cx: i32, cz: i32) -> bool;
|
||||
/// The `gameplay/can_pillager_patrol_spawn` environment attribute.
|
||||
fn can_pillager_patrol_spawn(&self, pos: [i32; 3]) -> bool;
|
||||
/// `getCurrentDifficultyAt(pos).getEffectiveDifficulty()`.
|
||||
fn effective_difficulty(&self, pos: [i32; 3]) -> f32;
|
||||
/// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` height of a column.
|
||||
fn motion_blocking_no_leaves(&self, x: i32, z: i32) -> i32;
|
||||
}
|
||||
|
||||
/// `ServerLevel.isCloseToVillage`.
|
||||
pub fn close_to_village<L: PatrolLevel + ?Sized>(l: &L, pos: [i32; 3], sections: i32) -> bool {
|
||||
sections <= 6 && l.sections_to_village(pos) <= sections
|
||||
}
|
||||
|
||||
/// `Level.hasChunksAt(x0, z0, x1, z1)`.
|
||||
pub fn has_chunks_at<L: PatrolLevel + ?Sized>(l: &L, x0: i32, z0: i32, x1: i32, z1: i32) -> bool {
|
||||
(x0 >> 4..=x1 >> 4).all(|cx| (z0 >> 4..=z1 >> 4).all(|cz| l.has_chunk(cx, cz)))
|
||||
}
|
||||
|
||||
/// A pillager the spawner asks for: where, and whether it leads the patrol.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Member {
|
||||
pub pos: [i32; 3],
|
||||
pub leader: bool,
|
||||
}
|
||||
|
||||
/// `PatrolSpawner` (its countdown lives in memory: a fresh level tries at once).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PatrolSpawner {
|
||||
pub next_tick: i32,
|
||||
}
|
||||
|
||||
impl PatrolSpawner {
|
||||
/// `PatrolSpawner.tick`. `spawn_enemies` is the chunk source's flag
|
||||
/// (`spawn_mobs` and `spawn_monsters`); `random` is the level random.
|
||||
/// `spawn` creates, finalizes and adds a pillager at a position that
|
||||
/// passed the spawn checks (`EntityType.create` succeeding), and says
|
||||
/// whether it did.
|
||||
pub fn tick<L: PatrolLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
level: &L,
|
||||
spawn_enemies: bool,
|
||||
random: &mut R,
|
||||
spawn: &mut dyn FnMut(&L, Member, &mut R) -> bool,
|
||||
) {
|
||||
if !spawn_enemies || !level.spawn_patrols() {
|
||||
return;
|
||||
}
|
||||
self.next_tick -= 1;
|
||||
if self.next_tick > 0 {
|
||||
return;
|
||||
}
|
||||
self.next_tick += 12000 + random.next_int_bound(1200).unwrap_or(0);
|
||||
if !level.bright_outside() || random.next_int_bound(5).unwrap_or(1) != 0 {
|
||||
return;
|
||||
}
|
||||
let players = level.patrol_players();
|
||||
if players.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (player, spectator) =
|
||||
players[random.next_int_bound(players.len() as i32).unwrap_or(0) as usize];
|
||||
if spectator || close_to_village(level, player, 2) {
|
||||
return;
|
||||
}
|
||||
let x = (24 + random.next_int_bound(24).unwrap_or(0))
|
||||
* if random.next_boolean() { -1 } else { 1 };
|
||||
let z = (24 + random.next_int_bound(24).unwrap_or(0))
|
||||
* if random.next_boolean() { -1 } else { 1 };
|
||||
let mut pos = [player[0] + x, player[1], player[2] + z];
|
||||
if !has_chunks_at(level, pos[0] - 10, pos[2] - 10, pos[0] + 10, pos[2] + 10)
|
||||
|| !level.can_pillager_patrol_spawn(pos)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let group = level.effective_difficulty(pos).ceil() as i32 + 1;
|
||||
for i in 0..group {
|
||||
pos[1] = level.motion_blocking_no_leaves(pos[0], pos[2]);
|
||||
let leader = i == 0;
|
||||
if !spawn_member(level, pos, leader, random, spawn) && leader {
|
||||
break;
|
||||
}
|
||||
pos[0] += random.next_int_bound(5).unwrap_or(0) - random.next_int_bound(5).unwrap_or(0);
|
||||
pos[2] += random.next_int_bound(5).unwrap_or(0) - random.next_int_bound(5).unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `PatrolSpawner.spawnPatrolMember`: an empty spawn block for a pillager
|
||||
/// whose `checkPatrollingMonsterSpawnRules` pass.
|
||||
fn spawn_member<L: PatrolLevel, R: RandomSource>(
|
||||
level: &L,
|
||||
pos: [i32; 3],
|
||||
leader: bool,
|
||||
random: &mut R,
|
||||
spawn: &mut dyn FnMut(&L, Member, &mut R) -> bool,
|
||||
) -> bool {
|
||||
let [x, y, z] = pos;
|
||||
if !spawn_rules::is_valid_empty_spawn(Species::Pillager, level, x, y, z) {
|
||||
return false;
|
||||
}
|
||||
if !spawn_rules::check_spawn_rules(Species::Pillager, level, Reason::Patrol, random, x, y, z) {
|
||||
return false;
|
||||
}
|
||||
spawn(level, Member { pos, leader }, random)
|
||||
}
|
||||
|
||||
/// `PatrollingMonster.findPatrolTarget` from a block position.
|
||||
pub fn patrol_target(at: [i32; 3], random: &mut impl RandomSource) -> [i32; 3] {
|
||||
let dx = -500 + random.next_int_bound(1000).unwrap_or(0);
|
||||
let dz = -500 + random.next_int_bound(1000).unwrap_or(0);
|
||||
[at[0] + dx, at[1], at[2] + dz]
|
||||
}
|
||||
|
||||
/// The boolean gameplay attributes patrols and raids read
|
||||
/// (`gameplay/can_pillager_patrol_spawn`, `gameplay/can_start_raid`): the
|
||||
/// dimension's value, the biome's, then the dimension's timelines (the early
|
||||
/// game timeline forbids patrols for the first 120,000 ticks of the
|
||||
/// overworld clock).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct GameplayAttributes {
|
||||
/// attribute -> dimension type -> value.
|
||||
dimensions: std::collections::HashMap<String, std::collections::HashMap<String, bool>>,
|
||||
/// attribute -> biome -> value.
|
||||
biomes: std::collections::HashMap<String, std::collections::HashMap<String, bool>>,
|
||||
/// attribute -> dimension type -> boolean tracks (keyframes, modifier).
|
||||
tracks: std::collections::HashMap<String, std::collections::HashMap<String, Vec<BoolTrack>>>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct BoolTrack {
|
||||
keyframes: Vec<(i64, bool)>,
|
||||
period: Option<i64>,
|
||||
modifier: String,
|
||||
}
|
||||
impl BoolTrack {
|
||||
/// `KeyframeTrackSampler.sample` for a value that is not interpolated.
|
||||
fn sample(&self, ticks: i64) -> bool {
|
||||
let t = match self.period {
|
||||
Some(p) if p > 0 => ticks.rem_euclid(p),
|
||||
_ => ticks,
|
||||
};
|
||||
let mut value = self.keyframes[0].1;
|
||||
for (at, v) in &self.keyframes {
|
||||
if t >= *at {
|
||||
value = *v;
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
fn apply(&self, base: bool, ticks: i64) -> bool {
|
||||
let arg = self.sample(ticks);
|
||||
match self.modifier.as_str() {
|
||||
"and" => base && arg,
|
||||
"or" => base || arg,
|
||||
"xor" => base ^ arg,
|
||||
"nand" => !(base && arg),
|
||||
"nor" => !(base || arg),
|
||||
"xnor" => base == arg,
|
||||
_ => arg,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub const CAN_PILLAGER_PATROL_SPAWN: &str = "minecraft:gameplay/can_pillager_patrol_spawn";
|
||||
pub const CAN_START_RAID: &str = "minecraft:gameplay/can_start_raid";
|
||||
impl GameplayAttributes {
|
||||
/// Reads the dimension types, biomes and timelines under `root/data`.
|
||||
pub fn load(root: &std::path::Path) -> Self {
|
||||
use serde_json::Value;
|
||||
let data = root.join("data/minecraft");
|
||||
let read = |p: std::path::PathBuf| -> Option<Value> {
|
||||
serde_json::from_slice(&std::fs::read(p).ok()?).ok()
|
||||
};
|
||||
let list = |dir: &str| -> Vec<(String, Value)> {
|
||||
let mut out = Vec::new();
|
||||
if let Ok(entries) = std::fs::read_dir(data.join(dir)) {
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
if let (Some(stem), Some(v)) = (
|
||||
path.file_stem().and_then(|s| s.to_str()).map(str::to_owned),
|
||||
read(path.clone()),
|
||||
) {
|
||||
out.push((format!("minecraft:{stem}"), v));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
let keys = [CAN_PILLAGER_PATROL_SPAWN, CAN_START_RAID];
|
||||
let mut out = Self::default();
|
||||
let timelines: std::collections::HashMap<String, Value> =
|
||||
list("timeline").into_iter().collect();
|
||||
// Tag values with nested tags resolved.
|
||||
fn tag(data: &std::path::Path, name: &str, out: &mut Vec<String>) {
|
||||
let file = data.join(format!(
|
||||
"tags/timeline/{}.json",
|
||||
name.trim_start_matches('#')
|
||||
.trim_start_matches("minecraft:")
|
||||
));
|
||||
let Some(v) = std::fs::read(file)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for item in v["values"].as_array().into_iter().flatten() {
|
||||
let s = item.as_str().or_else(|| item["id"].as_str()).unwrap_or("");
|
||||
if s.starts_with('#') {
|
||||
tag(data, s, out);
|
||||
} else if !s.is_empty() {
|
||||
out.push(s.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (dim, v) in list("dimension_type") {
|
||||
for key in keys {
|
||||
if let Some(b) = v["attributes"][key].as_bool() {
|
||||
out.dimensions
|
||||
.entry(key.into())
|
||||
.or_default()
|
||||
.insert(dim.clone(), b);
|
||||
}
|
||||
}
|
||||
let mut names = Vec::new();
|
||||
match &v["timelines"] {
|
||||
Value::String(s) if s.starts_with('#') => tag(&data, s, &mut names),
|
||||
Value::String(s) => names.push(s.clone()),
|
||||
Value::Array(a) => {
|
||||
names.extend(a.iter().filter_map(|x| x.as_str()).map(str::to_owned))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for name in names {
|
||||
let Some(t) = timelines.get(&name) else {
|
||||
continue;
|
||||
};
|
||||
for key in keys {
|
||||
let track = &t["tracks"][key];
|
||||
let Some(frames) = track["keyframes"].as_array() else {
|
||||
continue;
|
||||
};
|
||||
let keyframes: Vec<(i64, bool)> = frames
|
||||
.iter()
|
||||
.filter_map(|f| Some((f["ticks"].as_i64()?, f["value"].as_bool()?)))
|
||||
.collect();
|
||||
if keyframes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.tracks
|
||||
.entry(key.into())
|
||||
.or_default()
|
||||
.entry(dim.clone())
|
||||
.or_default()
|
||||
.push(BoolTrack {
|
||||
keyframes,
|
||||
period: t["period_ticks"].as_i64(),
|
||||
modifier: track["modifier"].as_str().unwrap_or("override").to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (biome, v) in list("worldgen/biome") {
|
||||
for key in keys {
|
||||
if let Some(b) = v["attributes"][key].as_bool() {
|
||||
out.biomes
|
||||
.entry(key.into())
|
||||
.or_default()
|
||||
.insert(biome.clone(), b);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The attribute in a dimension type and biome at an overworld clock time.
|
||||
pub fn value(&self, key: &str, dimension: &str, biome: &str, clock: i64) -> bool {
|
||||
let mut v = self
|
||||
.dimensions
|
||||
.get(key)
|
||||
.and_then(|m| m.get(dimension))
|
||||
.copied()
|
||||
.unwrap_or(true);
|
||||
if let Some(b) = self.biomes.get(key).and_then(|m| m.get(biome)) {
|
||||
v = *b;
|
||||
}
|
||||
for t in self
|
||||
.tracks
|
||||
.get(key)
|
||||
.and_then(|m| m.get(dimension))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
v = t.apply(v, clock);
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
+1098
-462
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user