Merge main into fix/sulfur-cube-inner-layer

Resolve minecarts.rs against the resources split (#537): the block model
catalog now lives in self.pack. Fill MobData's new villager_hats and pois
fields in the sulfur cube render test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 00:21:04 +02:00
289 changed files with 26929 additions and 2169 deletions
+11
View File
@@ -27,6 +27,13 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Does this pull request need Rust checks?
if: github.event_name == 'pull_request'
id: rust
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: python3 tools/ci/rust_changes.py "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT"
- name: Keep game artifacts out of Git
run: |
python tools/check_public_tree.py
@@ -34,19 +41,23 @@ jobs:
- name: Test offline research tooling
run: python -m unittest discover -s tests -v
- name: Install Rust toolchain and the ALSA and udev headers the client links against
if: steps.rust.outputs.required != 'false'
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
rustup toolchain install stable --profile minimal --component rustfmt --component clippy --target wasm32-unknown-unknown
# Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache).
- uses: Swatinem/rust-cache@v2
if: steps.rust.outputs.required != 'false'
with:
shared-key: verify
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Check formatting and lint
if: steps.rust.outputs.required != 'false'
run: |
cargo +stable fmt --all -- --check
cargo +stable clippy --workspace --all-targets -- -D warnings
- name: Test Rust core and voxel kernel correctness
if: steps.rust.outputs.required != 'false'
run: cargo +stable test --workspace
parity:
if: >-
+1 -1
View File
@@ -154,7 +154,7 @@ jobs:
client="$PWD/target/release/horizon-client"
resources="$PWD/.local/horizon-client/$version"
(cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \
--world smoke --seed 1 --render-distance 4 --frames 1500 --timeout-seconds 180 \
--world smoke --seed 1 --render-distance 4 --world-frames 1500 --timeout-seconds 180 \
--smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; }
python3 - "$home/smoke.json" <<'EOF'
import json, sys
+2
View File
@@ -24,6 +24,8 @@
/horizon.txt
/horizon-graphics.txt
/horizon-controller.txt
/horizon-extras.txt
/horizon-player.txt
/servers.dat
/screenshots/
/crash-reports/
Generated
+410 -6
View File
@@ -178,6 +178,15 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
[[package]]
name = "ascii-canvas"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1e3e699d84ab1b0911a1010c5c106aa34ae89aeac103be5ce0c3859db1e891"
dependencies = [
"term",
]
[[package]]
name = "ash"
version = "0.38.0+1.3.281"
@@ -205,15 +214,30 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec 0.8.0",
]
[[package]]
name = "bit-set"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
dependencies = [
"bit-vec",
"bit-vec 0.9.1",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bit-vec"
version = "0.9.1"
@@ -259,6 +283,16 @@ dependencies = [
"objc2 0.6.5",
]
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"bytes",
"cfg_aliases",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -450,6 +484,15 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "convert_case"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "coords-hud"
version = "0.1.0"
@@ -754,6 +797,41 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "darling"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 2.0.119",
]
[[package]]
name = "darling_macro"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
dependencies = [
"darling_core",
"quote",
"syn 2.0.119",
]
[[package]]
name = "dasp_sample"
version = "0.11.0"
@@ -771,6 +849,29 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "derive_more"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn 2.0.119",
"unicode-xid",
]
[[package]]
name = "digest"
version = "0.10.7"
@@ -857,6 +958,15 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]]
name = "ena"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
dependencies = [
"log",
]
[[package]]
name = "encoding_rs"
version = "0.8.42"
@@ -1120,6 +1230,58 @@ version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
[[package]]
name = "glsl-lang"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "983a18d0c2ecad18ac9ff3c94b069d6bd03b47405a200836d9d8d63def8e34de"
dependencies = [
"glsl-lang-lexer",
"glsl-lang-types",
"lalrpop",
"lalrpop-util",
"lang-util",
"once_cell",
"thiserror 2.0.21",
]
[[package]]
name = "glsl-lang-lexer"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abdbc0bdfbc81d557f4865e695457eb23d68031bfb061fda3444f56511b26eee"
dependencies = [
"glsl-lang-pp",
"glsl-lang-types",
"lalrpop-util",
"lang-util",
"thiserror 2.0.21",
]
[[package]]
name = "glsl-lang-pp"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88677876fb27f116015d0ecebda6d77bdf65f3a6fa3f5dfeed10b8c8f04cb2c5"
dependencies = [
"arrayvec",
"derive_more",
"lang-util",
"string_cache",
"string_cache_codegen",
"thiserror 2.0.21",
]
[[package]]
name = "glsl-lang-types"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd8b1532b424d40df634cf2dc2be56d59f994b9ac07fa7c1e3183fd33db9cb07"
dependencies = [
"lang-util",
"thiserror 2.0.21",
]
[[package]]
name = "gpu-allocator"
version = "0.28.0"
@@ -1255,6 +1417,7 @@ dependencies = [
"horizon-friends",
"horizon-mods",
"horizon-protocol",
"horizon-shaderpack",
"horizon-telemetry",
"horizon-theme",
"horizon-world",
@@ -1320,6 +1483,7 @@ dependencies = [
"horizon-mods",
"log",
"serde",
"serde_json",
"toml",
"wasmtime",
"wit-component 0.239.0",
@@ -1334,6 +1498,19 @@ dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "horizon-port-pack"
version = "0.1.0"
dependencies = [
"horizon-mods",
"serde",
"serde_json",
"sha1",
"toml",
"ureq",
"zip",
]
[[package]]
name = "horizon-prepare"
version = "0.1.0"
@@ -1364,6 +1541,16 @@ dependencies = [
"serde_json",
]
[[package]]
name = "horizon-shaderpack"
version = "0.1.0"
dependencies = [
"glsl-lang",
"naga",
"pp-rs",
"zip",
]
[[package]]
name = "horizon-telemetry"
version = "0.1.0"
@@ -1504,6 +1691,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
version = "1.1.0"
@@ -1686,6 +1879,73 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "keccak"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
dependencies = [
"cpufeatures",
]
[[package]]
name = "lalrpop"
version = "0.22.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba4ebbd48ce411c1d10fb35185f5a51a7bfa3d8b24b4e330d30c9e3a34129501"
dependencies = [
"ascii-canvas",
"bit-set 0.8.0",
"ena",
"itertools",
"lalrpop-util",
"petgraph 0.7.1",
"pico-args",
"regex",
"regex-syntax",
"sha3",
"string_cache",
"term",
"unicode-xid",
"walkdir",
]
[[package]]
name = "lalrpop-util"
version = "0.22.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5baa5e9ff84f1aefd264e6869907646538a52147a755d494517a8007fb48733"
dependencies = [
"regex-automata",
"rustversion",
]
[[package]]
name = "lang-util"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1715a1e56998f119cd6d49ac8a69802dcbe4fca96d8291243d6dae87abeb913"
dependencies = [
"derive_more",
"lalrpop-util",
"lang-util-derive",
"line-span",
"smol_str 0.3.6",
"text-size",
]
[[package]]
name = "lang-util-derive"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f2acc66aedf0e445534e0a6b3f0f6ee20ef6ebb9647dbe10735e52ea8d6a096"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "lazy_static"
version = "1.5.1"
@@ -1742,6 +2002,12 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "line-span"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fc123b2f6600099ca18248f69e3ee02b09c4188c0d98e9a690d90dec3e408a"
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -1853,7 +2119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
dependencies = [
"arrayvec",
"bit-set",
"bit-set 0.10.0",
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
@@ -1866,6 +2132,7 @@ dependencies = [
"naga-types",
"num-traits",
"once_cell",
"pp-rs",
"rustc-hash 1.1.0",
"spirv",
"thiserror 2.0.21",
@@ -1914,6 +2181,12 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.31.3"
@@ -2413,6 +2686,16 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"
dependencies = [
"fixedbitset",
"indexmap",
]
[[package]]
name = "petgraph"
version = "0.8.3"
@@ -2424,6 +2707,31 @@ dependencies = [
"indexmap",
]
[[package]]
name = "phf_generator"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
dependencies = [
"phf_shared",
"rand",
]
[[package]]
name = "phf_shared"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
dependencies = [
"siphasher",
]
[[package]]
name = "pico-args"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]]
name = "pin-project"
version = "1.1.13"
@@ -2542,6 +2850,21 @@ dependencies = [
"zerovec",
]
[[package]]
name = "pp-rs"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb458bb7f6e250e6eb79d5026badc10a3ebb8f9a15d1fff0f13d17c71f4d6dee"
dependencies = [
"unicode-xid",
]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "presser"
version = "0.3.1"
@@ -2635,6 +2958,15 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
@@ -2967,6 +3299,16 @@ dependencies = [
"digest",
]
[[package]]
name = "sha3"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"
dependencies = [
"digest",
"keccak",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -2995,6 +3337,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "siphasher"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "slab"
version = "0.4.12"
@@ -3044,6 +3392,16 @@ dependencies = [
"serde",
]
[[package]]
name = "smol_str"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523"
dependencies = [
"borsh",
"serde_core",
]
[[package]]
name = "socket2"
version = "0.5.10"
@@ -3093,6 +3451,37 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
[[package]]
name = "string_cache"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f"
dependencies = [
"new_debug_unreachable",
"parking_lot",
"phf_shared",
"precomputed-hash",
"serde",
]
[[package]]
name = "string_cache_codegen"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0"
dependencies = [
"phf_generator",
"phf_shared",
"proc-macro2",
"quote",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
@@ -3209,6 +3598,15 @@ version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "term"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8c27177b12a6399ffc08b98f76f7c9a1f4fe9fc967c784c5a071fa8d93cf7e1"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"
@@ -3218,6 +3616,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "text-size"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233"
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -3377,7 +3781,7 @@ checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
dependencies = [
"memchr",
"nom",
"petgraph",
"petgraph 0.8.3",
]
[[package]]
@@ -4098,8 +4502,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"
dependencies = [
"arrayvec",
"bit-set",
"bit-vec",
"bit-set 0.10.0",
"bit-vec 0.9.1",
"bitflags 2.13.2",
"bytemuck",
"cfg_aliases",
@@ -4645,7 +5049,7 @@ dependencies = [
"rustix 0.38.44",
"sctk-adwaita",
"smithay-client-toolkit",
"smol_str",
"smol_str 0.2.2",
"tracing",
"unicode-segmentation",
"wasm-bindgen",
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
resolver = "2"
[workspace.package]
+2
View File
@@ -27,6 +27,8 @@ serde_json = { version = "1.0.151", features = ["raw_value"] }
# Shader packs: pack.toml, and WGSL checked before it reaches wgpu.
toml = "1.1"
naga = { version = "30.0.1", features = ["wgsl-in"] }
# Java (OptiFine/Iris) shader packs, translated to WGSL.
horizon-shaderpack = { path = "../horizon-shaderpack" }
cpal = "0.16"
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
miniz_oxide = "0.8"
@@ -100,6 +100,7 @@ fn main() -> Result<()> {
player.auto_jump_enabled = p["enabled"].as_bool().unwrap();
player.auto_jump_time = p["time"].as_i64().unwrap() as i32;
MotionWorld {
entities: &[],
player: &mut player,
scene: &mut scene,
assets: &assets,
+16 -5
View File
@@ -19,7 +19,7 @@ use horizon_client::{
},
mobs::{
Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who,
control::Operation, spawning::LocalDifficulty,
control::Operation, seen_grid::SeenGrid, spawning::LocalDifficulty,
},
world::World,
};
@@ -902,6 +902,10 @@ fn main() -> horizon_client::Result<()> {
for flag in &spec.flags {
match flag.as_str() {
"persistent" => m.persistent = true,
"ridden" => {
m.extra.head = Some("minecraft:red_harness".into());
m.rider = Some(horizon_client::mobs::equine::Rider::default());
}
"noai" => m.no_ai = true,
// Warden.finalizeSpawn's own part.
"digcooldown" | "emerge" => horizon_client::mobs::warden::finalize(
@@ -1007,6 +1011,9 @@ fn main() -> horizon_client::Result<()> {
// The MobWorld every step sees, over a snapshot of the mobs.
macro_rules! mob_world {
($snapshot:expr) => {
mob_world!($snapshot, None)
};
($snapshot:expr, $grid:expr) => {
MobWorld {
teams: Default::default(),
world: &world,
@@ -1017,6 +1024,7 @@ fn main() -> horizon_client::Result<()> {
data: &data,
player: player.clone(),
others: $snapshot,
others_grid: $grid,
daylight: (world.day_time.rem_euclid(24000)) < 12000,
game_time: world.game_time,
day_time: world.day_time,
@@ -1061,6 +1069,8 @@ fn main() -> horizon_client::Result<()> {
p.yaw = yaw;
}
let mut snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
// The snapshot by position, kept as the game keeps it.
let mut grid = SeenGrid::new(snapshot.iter().map(|e| e.bounds));
let w = mob_world!(&snapshot);
let mut events = Vec::new();
let mut heart_events = Vec::new();
@@ -1126,7 +1136,7 @@ fn main() -> horizon_client::Result<()> {
if mobs[i].removed {
continue;
}
let w = mob_world!(&snapshot);
let w = mob_world!(&snapshot, Some(&grid));
let m = &mut mobs[i];
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
let from = events.len();
@@ -1242,9 +1252,10 @@ fn main() -> horizon_client::Result<()> {
}
// 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;
if let Some(k) = snapshot.iter().position(|e| e.id == mobs[i].id) {
snapshot[k] = seen(&mobs[i]);
snapshot[k].alive &= !mobs[i].removed;
grid.update(k, snapshot[k].bounds);
}
}
for m in &mut mobs {
@@ -17,13 +17,16 @@
//! a `mobs::trial_spawner::TrialSpawner` with the game time advancing and
//! print its states, events, spawns and ejected items.
//!
//! Vault cases (`mode=vault`, tools/test_vault_parity.py) tick a
//! `vault::Vault` the same way, with players moving and using keys on it.
//!
//! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
assets::Assets,
biome::{Biomes, SpawnEntry},
blocks::BlockFacts,
collisions::{self, LookupCollisions, no_collision_empty},
items::Items,
items::{ItemStack, Items},
mobs::{
MobTypes, Species,
data::MobData,
@@ -35,8 +38,12 @@ use horizon_client::{
},
spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn},
species::{self, Baby},
trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState},
trial_spawner::{
Omen, TRIAL_OMEN_TICKS_PER_LEVEL, TrialEvent, TrialPlayer, TrialSpawner,
TrialSpawnerLevel, TrialState,
},
},
vault::{Vault, VaultEvent, VaultLevel, VaultPlayer, VaultState},
};
use horizon_core::{
geometry::Aabb,
@@ -115,8 +122,14 @@ struct World<'a> {
placed: RefCell<Vec<([i32; 3], BlockStateId)>>,
/// The game time (trial cases advance it).
time: Cell<i64>,
/// The mobs a trial spawner added: UUID, position and box.
trial_mobs: RefCell<Vec<([i32; 4], [f64; 3], Aabb)>>,
/// The mobs a trial spawner added: UUID, position, height and box.
trial_mobs: RefCell<Vec<([i32; 4], [f64; 3], f32, Aabb)>>,
/// How many mobs a trial spawner added (their UUIDs count up).
trial_count: Cell<i32>,
/// Each player's omen and its amplifier (`/trial_omen:A`, `/bad_omen:A`).
omens: RefCell<Vec<Option<(Omen, i32)>>>,
/// Loot tables (trial cases).
loot: Option<std::sync::Arc<horizon_world::loot::LootData>>,
}
impl World<'_> {
fn biome_at(&self, x: i32, y: i32, z: i32) -> &str {
@@ -378,6 +391,16 @@ impl TrialSpawnerLevel for World<'_> {
eye: [p[0], p[1] + f64::from(1.62f32), p[2]],
creative: mode == "creative",
spectator: mode == "spectator",
position: *p,
height: 1.8,
alive: true,
omen: self
.omens
.borrow()
.get(i)
.copied()
.flatten()
.map(|(o, _)| o),
})
.collect()
}
@@ -400,9 +423,38 @@ impl TrialSpawnerLevel for World<'_> {
}
fn entity_block(&self, uuid: [i32; 4]) -> Option<[i32; 3]> {
let mobs = self.trial_mobs.borrow();
let (_, p, _) = mobs.iter().find(|(u, ..)| *u == uuid)?;
let (_, p, ..) = mobs.iter().find(|(u, ..)| *u == uuid)?;
Some(p.map(|v| v.floor() as i32))
}
fn entity_box(&self, uuid: [i32; 4]) -> Option<([f64; 3], f32)> {
let mobs = self.trial_mobs.borrow();
let (_, p, h, _) = mobs.iter().find(|(u, ..)| *u == uuid)?;
Some((*p, *h))
}
fn no_block_collision(&self, block: [i32; 3]) -> bool {
let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z);
let mut scene = LookupCollisions {
block: &lookup,
binding: self.s.collision,
};
let state = self.state(block[0], block[1], block[2]);
self.s
.collision
.collision_shape(&mut scene, state, block)
.map_or(true, |shape| shape.is_empty())
}
fn loot_items(&self, table: &str, seed: i64) -> Vec<horizon_client::items::ItemStack> {
let Some(loot) = &self.loot else {
return Vec::new();
};
loot.roll_split(table, &mut LegacyRandom::new(seed))
.iter()
.map(horizon_client::structure_blocks::loot_item_with_components)
.collect()
}
fn seed(&self) -> i64 {
self.seed
}
}
/// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random.
@@ -472,7 +524,7 @@ fn main() -> horizon_client::Result<()> {
let data = MobData::load(root, &facts);
let items = Items::tags_only(root)?;
// Trial spawner rewards: the loot tables and the configs.
let loot = if input.contains("mode=trial") {
let loot = if input.contains("mode=trial") || input.contains("mode=vault") {
horizon_client::mobs::trial_spawner::load_registry(root);
horizon_client::structure_blocks::loot_data(root)
} else {
@@ -581,6 +633,19 @@ fn main() -> horizon_client::Result<()> {
bounds: Bx(b),
});
}
// A player's third field: an omen and its amplifier.
let omens = indexed("p")
.iter()
.map(|p| {
let (effect, amplifier) = p.split('/').nth(2)?.split_once(':')?;
let omen = if effect == "trial_omen" {
Omen::Trial
} else {
Omen::Bad
};
Some((omen, amplifier.parse().ok()?))
})
.collect();
let players = indexed("p")
.into_iter()
.map(|p| {
@@ -667,6 +732,9 @@ fn main() -> horizon_client::Result<()> {
placed: RefCell::new(Vec::new()),
time: Cell::new(0),
trial_mobs: RefCell::new(Vec::new()),
trial_count: Cell::new(0),
omens: RefCell::new(omens),
loot: loot.clone(),
entities: RefCell::new(
case_entities
.iter()
@@ -706,6 +774,9 @@ fn main() -> horizon_client::Result<()> {
} else if mode == "trial" {
let loot = loot.as_ref().ok_or("no loot tables")?;
trial_case(&world, registry, loot, &get, &mut random, &mut log)?;
} else if mode == "vault" {
let loot = loot.as_ref().ok_or("no loot tables")?;
vault_case(world.players.clone(), loot, &get, &mut random, &mut log)?;
} else if mode == "gen" {
let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?);
// The level random of the spawn predicates: no creature's predicate
@@ -972,8 +1043,22 @@ fn trial_case(
let scale = size as f32;
let bounds = spawn_box(x, y, z, t.width as f32 * scale, t.height as f32 * scale);
l.entities.borrow_mut().push((r.id.to_owned(), bounds));
let uuid = [1, 0, 0, l.trial_mobs.borrow().len() as i32];
l.trial_mobs.borrow_mut().push((uuid, r.position, bounds));
let uuid = [1, 0, 0, l.trial_count.get()];
l.trial_count.set(l.trial_count.get() + 1);
// Zombie.readAdditionalSaveData: IsBaby halves the box
// (getAgeScale); finalizeSpawn's fixed random never makes one.
let baby = match r
.entity
.get(&horizon_world::nbt::JavaString::from("IsBaby"))
{
Some(Tag::Byte(v)) => *v != 0,
Some(Tag::Int(v)) => *v != 0,
_ => false,
};
let height = t.height as f32 * scale * if baby { 0.5 } else { 1.0 };
l.trial_mobs
.borrow_mut()
.push((uuid, r.position, height, bounds));
spawned.push_back(format!(
"{tick} spawn {} {} {} {} {}",
r.id,
@@ -1028,7 +1113,7 @@ fn trial_case(
for e in events {
match e {
TrialEvent::BlockUpdated => log.push(format!("{tick} update")),
TrialEvent::LevelEvent(id, _, data) => {
TrialEvent::LevelEvent(id, p, data) => {
// A spawn's events follow its tryAddFreshEntityWithPassengers,
// a reward's its items.
match id {
@@ -1036,7 +1121,13 @@ fn trial_case(
3014 => log.append(&mut items),
_ => {}
}
log.push(format!("{tick} levent {id} {data}"));
match id {
3020 | 3012 => log.push(format!(
"{tick} levent {id} {data} at {},{},{}",
p[0], p[1], p[2]
)),
_ => log.push(format!("{tick} levent {id} {data}")),
}
}
TrialEvent::Sound(name) => log.push(format!(
"{tick} sound minecraft:{name} {} {} {} 1.0 1.0",
@@ -1048,6 +1139,44 @@ fn trial_case(
"{tick} gevent minecraft:entity_place {} {} {}",
p[0], p[1], p[2]
)),
TrialEvent::TrialOmen(uuid) => {
let i = (uuid[3] - 1) as usize;
let mut omens = world.omens.borrow_mut();
let amplifier = omens.get(i).copied().flatten().map_or(0, |(_, a)| a);
log.push(format!("{tick} effect remove minecraft:bad_omen"));
log.push(format!(
"{tick} effect add minecraft:trial_omen {} 0",
TRIAL_OMEN_TICKS_PER_LEVEL * (amplifier + 1)
));
if let Some(o) = omens.get_mut(i) {
*o = Some((Omen::Trial, 0));
}
}
TrialEvent::Discard(uuid) => {
let mut mobs = world.trial_mobs.borrow_mut();
if let Some(i) = mobs.iter().position(|(u, ..)| *u == uuid) {
let (.., b) = mobs.remove(i);
world.entities.borrow_mut().retain(|(_, e)| *e != b);
}
}
TrialEvent::SoundAt(name, b, pitch) => log.push(format!(
"{tick} sound minecraft:{name} {} {} {} 1.0 {pitch:?}",
bits(f64::from(b[0]) + 0.5),
bits(f64::from(b[1]) + 0.5),
bits(f64::from(b[2]) + 0.5)
)),
TrialEvent::ItemSpawner {
item,
position,
delay,
} => log.push(format!(
"{tick} ispawner {} {} {} {} {} {delay}",
item.item,
item.count,
bits(position[0]),
bits(position[1]),
bits(position[2])
)),
TrialEvent::OminousSet(set) => {
ominous = set;
world
@@ -1101,3 +1230,195 @@ fn trial_case(
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
Ok(())
}
/// What a vault reads: the game time and the case's players, moved by `move`.
struct VaultWorld {
time: i64,
players: Vec<([f64; 3], String)>,
}
impl VaultLevel for VaultWorld {
fn game_time(&self) -> i64 {
self.time
}
fn players(&self) -> Vec<VaultPlayer> {
self.players
.iter()
.enumerate()
.map(|(i, (p, mode))| VaultPlayer {
uuid: [0, 0, 0, i as i32 + 1],
block: p.map(|v| v.floor() as i32),
spectator: mode == "spectator",
})
.collect()
}
}
/// A UUID's low 64 bits, as the oracle prints players.
fn uuid_low(u: &[i32; 4]) -> String {
((i64::from(u[2]) << 32) | i64::from(u[3] as u32)).to_string()
}
/// The display item and the connected players as the oracle prints them.
fn vault_shared(v: &Vault) -> String {
let mut connected: Vec<String> = v.connected_players.iter().map(uuid_low).collect();
connected.sort();
format!(
"{} [{}]",
v.display_item
.as_ref()
.map_or_else(|| "-".to_owned(), |s| format!("{}*{}", s.item, s.count)),
connected.join(",")
)
}
/// `VaultBlockEntity.Server.tick` `ticks` times from game time `t0` at `spos`
/// on a vault block in state `state` (ominous with `ominous=1`) loaded from
/// `snbt` (base64 SNBT), with the case's key uses (`use`) and player moves
/// (`move`) before each tick, as the oracle logs it.
fn vault_case(
players: Vec<([f64; 3], String)>,
loot: &horizon_world::loot::LootData,
get: &dyn Fn(&str, &'static str) -> String,
random: &mut LegacyRandom,
log: &mut Vec<String>,
) -> horizon_client::Result<()> {
let v: Vec<i32> = get("spos", "0,0,0")
.split(',')
.map(|n| n.parse().unwrap_or(0))
.collect();
let pos = [v[0], v[1], v[2]];
let mut state = VaultState::from_name(&get("state", "inactive")).ok_or("bad state")?;
let ominous = get("ominous", "0") == "1";
let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?;
let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0;
let mut vault = Vault::load(&tag);
let schedule = |key: &str| -> Vec<Vec<String>> {
get(key, "")
.split(';')
.filter(|s| !s.is_empty())
.map(|s| s.split('/').map(str::to_owned).collect())
.collect()
};
let (uses, moves) = (schedule("use"), schedule("move"));
let ticks: i64 = get("ticks", "1").parse()?;
let t0: i64 = get("t0", "0").parse()?;
let seed: i64 = get("wseed", "0").parse()?;
let mut sequences = horizon_client::random_sequences::RandomSequences::default();
let mut world = VaultWorld { time: t0, players };
let center = pos.map(|v| f64::from(v) + 0.5);
for tick in 0..ticks {
world.time = t0 + tick;
let at = |s: &[String]| s[0].parse() == Ok(tick);
for m in moves.iter().filter(|m| at(m)) {
let v: Vec<f64> = m[2].split(',').map(|n| n.parse().unwrap_or(0.0)).collect();
world.players[m[1].parse::<usize>()?].0 = [v[0], v[1], v[2]];
}
let mut events = Vec::new();
let mut roll = |table: &str, random: &mut LegacyRandom, sequence: bool| {
let drops = match loot.random_sequence(table).filter(|_| sequence) {
Some(s) => loot.roll_split(table, sequences.get(s, seed)),
None => loot.roll_split(table, random),
};
drops
.iter()
.map(horizon_client::structure_blocks::loot_item_with_components)
.collect()
};
for u in uses.iter().filter(|u| at(u)) {
let player: usize = u[1].parse()?;
let mut stack = ItemStack::new(&u[2], u[3].parse()?);
let used = vault.use_item_on(
&world,
random,
pos,
state,
ominous,
[0, 0, 0, player as i32 + 1],
Some(&stack),
&mut roll,
&mut events,
);
if world.players[player].1 != "creative" {
stack.count -= used.unwrap_or(0);
}
vault_events(&mut events, &mut state, ominous, tick, center, &vault, log);
log.push(format!(
"{tick} use {} {}",
if used.is_some() { "ok" } else { "pass" },
stack.count
));
}
vault.server_tick(&world, random, pos, state, ominous, &mut roll, &mut events);
vault_events(&mut events, &mut state, ominous, tick, center, &vault, log);
}
let saved = vault.save();
let config = saved
.iter()
.find(|(k, _)| *k == "config")
.and_then(|(_, t)| match t {
Tag::Compound(c) => {
let mut keys: Vec<String> = c.keys().map(|k| k.to_string_lossy()).collect();
keys.sort();
Some(keys.join(","))
}
_ => None,
})
.unwrap_or_default();
let eject: Vec<String> = vault
.items_to_eject
.iter()
.map(|s| format!("{}*{}", s.item, s.count))
.collect();
log.push(format!(
"end state={} rewarded={} resumes={} eject={} total={} shared={} config={config}",
state.name(),
vault
.rewarded_players
.iter()
.map(uuid_low)
.collect::<Vec<_>>()
.join(","),
vault.state_updating_resumes_at,
eject.join(","),
vault.total_ejections_needed,
vault_shared(&vault),
));
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
Ok(())
}
/// Logs a vault's events and applies its state changes.
fn vault_events(
events: &mut Vec<VaultEvent>,
state: &mut VaultState,
ominous: bool,
tick: i64,
center: [f64; 3],
vault: &Vault,
log: &mut Vec<String>,
) {
for e in events.drain(..) {
match e {
VaultEvent::State(s) => {
*state = s;
log.push(format!("{tick} state {} {ominous}", s.name()));
}
VaultEvent::BlockUpdated => log.push(format!("{tick} update {}", vault_shared(vault))),
VaultEvent::LevelEvent(id, data) => log.push(format!("{tick} levent {id} {data}")),
VaultEvent::Sound(name, volume, pitch) => log.push(format!(
"{tick} sound minecraft:{name} {} {} {} {volume:?} {pitch:?}",
bits(center[0]),
bits(center[1]),
bits(center[2])
)),
VaultEvent::Eject(stack, v) => log.push(format!(
"{tick} item {} {} {} {} {} {} {} {}",
stack.item,
stack.count,
bits(center[0]),
bits(center[1] + 0.7 - 0.125),
bits(center[2]),
bits(v[0]),
bits(v[1]),
bits(v[2])
)),
}
}
}
@@ -0,0 +1,96 @@
//! Block entity data on items for tools/test_pick_block_data_parity.py: reads
//! one JSON case per line (see VanillaPickBlockDataOracle) and prints the
//! picked item's component patch, a tab, then the placed block entity.
//!
//! usage: pick_block_data_fixture INPUT OUTPUT
use horizon_client::block_entity_item::{pick, place};
use horizon_client::block_entity_nbt::canonical;
use horizon_client::java_text::{double_to_string, float_to_string};
use horizon_world::nbt::{Tag, parse_snbt};
use serde_json::Value;
use std::fs;
/// ParityData.canon: sorted keys, typed numbers, Java's float text.
fn canon(tag: &Tag, out: &mut String) {
let join = |out: &mut String, prefix: &str, items: Vec<String>| {
out.push_str(prefix);
out.push_str(&items.join(","));
out.push(']');
};
match tag {
Tag::Float(v) => out.push_str(&format!("{}f", float_to_string(f32::from_bits(*v)))),
Tag::Double(v) => out.push_str(&format!("{}d", double_to_string(f64::from_bits(*v)))),
Tag::List(items) => join(
out,
"[",
items
.iter()
.map(|t| {
let mut s = String::new();
canon(t, &mut s);
s
})
.collect(),
),
Tag::Compound(map) => {
let mut keys: Vec<_> = map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
out.push('{');
for (i, (k, v)) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&k);
out.push(':');
canon(v, out);
}
out.push('}');
}
other => out.push_str(&horizon_client::item_data::canon_tag(other)),
}
}
fn snbt(value: &Value) -> Option<Tag> {
parse_snbt(value.as_str()?).ok().map(|(tag, _)| tag)
}
fn case(line: &str) -> Option<String> {
let case: Value = serde_json::from_str(line).ok()?;
let saved = canonical(&snbt(&case["nbt"])?)?;
let picked = pick(&saved);
let patch = match case.get("patch") {
Some(p) => match snbt(p)? {
Tag::Compound(c) => c,
_ => return None,
},
None => picked.clone(),
};
let target = canonical(&snbt(&case["target"])?)?;
let Tag::Compound(mut placed) = place(&target, &patch, case["op"].as_bool()?) else {
return None;
};
// keepPacked is the chunk's, not saveWithFullMetadata's.
placed.remove(&"keepPacked".into());
let mut out = String::new();
canon(&Tag::Compound(picked), &mut out);
out.push('\t');
canon(&Tag::Compound(placed), &mut out);
Some(out)
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let input = fs::read_to_string(
args.get(1)
.ok_or("usage: pick_block_data_fixture INPUT OUTPUT")?,
)?;
let lines: Vec<String> = input
.lines()
.map(|line| case(line).unwrap_or_else(|| "error".to_owned()))
.collect();
fs::write(
args.get(2).ok_or("missing OUTPUT")?,
lines.join("\n") + "\n",
)?;
Ok(())
}
@@ -2,6 +2,11 @@
#![forbid(unsafe_code)]
use horizon_client::{assets, collisions, world};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::{
collision_context::CollisionContext,
entity_obstruction::EntityIdentity,
world_movement::{self, CollisionCheckRequest, MovementRequest},
};
use serde_json::Value;
use std::{
fs,
@@ -57,21 +62,55 @@ fn main() -> Result<()> {
f["step"].as_str().ok_or("expected step bits")?,
16,
)?);
let movement = scene.resolve(
bounds,
delta,
step,
f["grounded"].as_bool().ok_or("expected grounded flag")?,
let entities = f["entities"]
.as_array()
.into_iter()
.flatten()
.map(|v| {
let a = v.as_array().ok_or("expected entity box")?;
Ok(Aabb::new(
vector(&Value::Array(a[..3].to_vec()))?,
vector(&Value::Array(a[3..].to_vec()))?,
))
})
.collect::<Result<Vec<_>>>()?;
let mut selected = collisions::EntityCollisions {
blocks: scene,
entities: &entities,
};
let movement = world_movement::resolve_world_movement(
&mut selected,
MovementRequest {
entity: EntityIdentity(0),
context: CollisionContext::position(bounds.min_position().y),
bounds,
movement: delta,
max_step: step,
on_ground: f["grounded"].as_bool().ok_or("expected grounded flag")?,
candidate_budget: 1_000_000,
},
)?;
let mut unobstructed = |bounds: Aabb| {
world_movement::no_world_collision(
&mut selected,
CollisionCheckRequest {
entity: EntityIdentity(0),
context: CollisionContext::position(bounds.min_position().y),
bounds,
candidate_budget: 1_000_000,
},
)
};
writeln!(
output,
"move {:016x} {:016x} {:016x} clear {} {}",
movement.x.to_bits(),
movement.y.to_bits(),
movement.z.to_bits(),
scene.unobstructed(bounds)?,
scene.unobstructed(bounds.move_by(movement))?
unobstructed(bounds)?,
unobstructed(bounds.move_by(movement))?
)?;
scene = selected.blocks;
}
Ok(())
}
@@ -298,6 +298,7 @@ fn main() -> Result<()> {
let mut travel: Option<horizon_core::position::BlockPos> = None;
for op in f["ops"].as_array().unwrap() {
let mut world = MotionWorld {
entities: &[],
player: &mut player,
scene: &mut scene,
assets: &assets,
@@ -0,0 +1,227 @@
//! The chunk pipeline (generation, decoration, lighting, meshing) on its worker
//! pool, without a window: how fast a render distance fills with N workers, and
//! what the render thread pays for it in `Streaming::update`.
//!
//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F]
//!
//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x
//! at that speed for T seconds while frames run at F per second. Each phase reports
//! its wall time, chunks generated and sections meshed, and the time `update`
//! took on the calling thread (the render thread in the game): total, median,
//! p99 and slowest. Compile with HORIZON_BENCH_COUNT_ALLOCATIONS=1 to count the
//! allocations made on the calling thread during updates and by everything.
use horizon_client::{
assets::Assets,
biome::Biomes,
blocks::BlockFacts,
light::LightTables,
mesher::MeshTables,
models,
streaming::{Streaming, WorkerContext},
vanillagen::VanillaTerrain,
world::World,
};
use std::{
alloc::{GlobalAlloc, Layout, System},
cell::Cell,
path::PathBuf,
sync::{
Arc,
atomic::{AtomicU64, Ordering::Relaxed},
},
time::{Duration, Instant},
};
const TRACK: bool = option_env!("HORIZON_BENCH_COUNT_ALLOCATIONS").is_some();
static ALLOCATIONS: AtomicU64 = AtomicU64::new(0);
static BYTES: AtomicU64 = AtomicU64::new(0);
thread_local! {
static LOCAL: Cell<(u64, u64)> = const { Cell::new((0, 0)) };
}
fn count(size: usize) {
if TRACK {
ALLOCATIONS.fetch_add(1, Relaxed);
BYTES.fetch_add(size as u64, Relaxed);
let _ = LOCAL.try_with(|c| {
let (n, b) = c.get();
c.set((n + 1, b + size as u64));
});
}
}
struct CountingAllocator;
// Delegates every operation and layout unchanged to System.
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
count(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
count(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) };
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 {
count(size);
unsafe { System.realloc(ptr, layout, size) }
}
}
#[global_allocator]
static ALLOCATOR: CountingAllocator = CountingAllocator;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Default)]
struct Phase {
updates: Vec<f64>,
local: (u64, u64),
uploads: usize,
}
impl Phase {
fn update(&mut self, streaming: &mut Streaming, world: &mut World) {
let before = LOCAL.with(Cell::get);
let started = Instant::now();
let (uploads, _) = streaming.update(world);
self.updates.push(started.elapsed().as_secs_f64() * 1e3);
let after = LOCAL.with(Cell::get);
self.local.0 += after.0 - before.0;
self.local.1 += after.1 - before.1;
self.uploads += uploads.len();
drop(uploads);
}
fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) {
let mut sorted = self.updates.clone();
sorted.sort_by(f64::total_cmp);
let at = |p: f64| sorted[((sorted.len() as f64 * p) as usize).min(sorted.len() - 1)];
let total: f64 = sorted.iter().sum();
println!(
"{name}: {:.2} s, {} chunks generated, {} sections meshed; update {:.1} ms total over {} calls, p50 {:.3} p99 {:.3} max {:.2} ms",
wall.as_secs_f64(),
streaming.generated_total - generated,
self.uploads,
total,
sorted.len(),
at(0.5),
at(0.99),
sorted.last().copied().unwrap_or(0.0),
);
if TRACK {
println!(
" update allocations: {} ({:.1} MiB)",
self.local.0,
self.local.1 as f64 / 1048576.0
);
}
}
}
/// Nothing queued or in flight. Sections at the edge of the area stay dirty
/// (their outer neighbours are never lit), so they don't count.
fn settled(streaming: &Streaming) -> bool {
streaming
.stages()
.iter()
.all(|&(name, n)| name == "protos" || n == 0)
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let root = PathBuf::from(args.first().ok_or("usage: streaming_bench RESOURCES")?);
let flag = |name: &str, default: f64| -> f64 {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1))
.and_then(|v| v.parse().ok())
.unwrap_or(default)
};
let auto = std::thread::available_parallelism().map_or(2, |n| n.get() - 1);
let threads = flag("--threads", auto as f64) as usize;
let radius = flag("--radius", 8.0) as i32;
let seed = flag("--seed", 1234.0) as i64;
let fly = flag("--fly", 0.0);
let seconds = flag("--seconds", 10.0);
let hz = flag("--hz", 240.0);
let assets = Arc::new(Assets::load(&root)?);
let facts = BlockFacts::load(&root, assets.registry)?;
let biomes = Arc::new(Biomes::load(&root)?);
let tables = Arc::new(MeshTables::new(
&assets,
&facts,
models::load_visibility(&root, assets.registry)?,
)?);
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
let terrain = Arc::new(VanillaTerrain::new(
&root.join("worldgen"),
assets.registry,
&biomes,
seed,
)?);
let context = Arc::new(WorkerContext {
assets,
tables,
biomes,
light,
});
let mut world = World::new(facts.air, seed);
let mut streaming = Streaming::new(terrain, context, threads);
streaming.radius = radius;
streaming.center = (0, 0);
println!("{threads} workers, radius {radius}, seed {seed}");
let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed));
// Fill: update as often as the game would uncapped, until settled.
let mut phase = Phase::default();
let started = Instant::now();
let mut quiet = 0;
while quiet < 20 {
let uploads = phase.uploads;
phase.update(&mut streaming, &mut world);
quiet = if settled(&streaming) && phase.uploads == uploads {
quiet + 1
} else {
0
};
std::thread::sleep(Duration::from_micros(500));
}
phase.report("fill", started.elapsed(), &streaming, 0);
if fly > 0.0 {
let mut phase = Phase::default();
let generated = streaming.generated_total;
let frame = Duration::from_secs_f64(1.0 / hz);
let started = Instant::now();
let mut behind = Vec::new();
while started.elapsed().as_secs_f64() < seconds {
let next = Instant::now() + frame;
let x = (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, 0);
phase.update(&mut streaming, &mut world);
// Columns within 2 chunks of the player still missing their meshes.
let near = (-2..=2)
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz)))
.filter(|&(cx, cz)| !streaming.is_lit(cx, cz))
.count();
behind.push(near);
if let Some(wait) = next.checked_duration_since(Instant::now()) {
std::thread::sleep(wait);
}
}
phase.report("fly", started.elapsed(), &streaming, generated);
let unlit = behind.iter().filter(|&&n| n > 0).count();
println!(
" frames with an unlit column within 2 chunks of the player: {unlit} of {} ({:.1}%)",
behind.len(),
unlit as f64 * 100.0 / behind.len().max(1) as f64
);
}
if TRACK {
println!(
"all threads: {} allocations ({:.1} MiB)",
ALLOCATIONS.load(Relaxed) - allocations,
(BYTES.load(Relaxed) - bytes) as f64 / 1048576.0
);
}
Ok(())
}
@@ -256,8 +256,9 @@ pub const COMMANDS: &[Cmd] = &[
&[opt("all", Ty::Bool, "drop the whole stack")], mcp: true, local: false),
cmd!("hold", Act, "hold KEY SECONDS", "press a key, wait, release it", "Keys as for key.", ["horizon-ctl hold w 2"],
&[p("key", Ty::Str, "key name"), p("seconds", Ty::Num, "how long")], mcp: false, local: true),
cmd!("key", Act, "key KEY down|up|tap", "press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", "",
["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false),
cmd!("key", Act, "key KEY down|up|tap|repeat", "press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
"down holds the key until key ... up, release or stop; wait does not release it. move, goto, jump, break and the other actions release the movement keys when they end.",
["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap", "repeat"]), "what to do")], mcp: true, local: false),
cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "",
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false),
cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them",
@@ -323,7 +324,9 @@ pub const COMMANDS: &[Cmd] = &[
cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false),
cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false),
cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false),
cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)", "", ["horizon-ctl wait 40"],
cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)",
"Keys and mouse buttons held with key ... down or mouse ... down stay held while it waits. Release them with key ... up, release or stop.",
["horizon-ctl wait 40", "horizon-ctl key w down && horizon-ctl wait 40 && horizon-ctl key w up"],
&[p("ticks", Ty::Int, "game ticks")], mcp: true, local: false),
// Scripting
cmd!("script", Scripting, "script [FILE] [--keep-going]", "run commands from FILE (or stdin), one per line",
@@ -0,0 +1,485 @@
//! Block entities carried by items, vanilla 26.3: Ctrl + Pick Block in creative
//! (`ServerGamePacketListenerImpl.addBlockDataToItem`) and placing such an item
//! (`BlockItem.updateCustomBlockEntityTag`, then
//! `BlockEntity.applyComponentsFromItemStack`). Both work on the block entity's
//! saved NBT (`block_entity_nbt::canonical`) and the item's component patch.
//!
//! What a type turns into item components (`removeComponentsFromTag`,
//! `collectImplicitComponents`) leaves its NBT; the rest goes to
//! `minecraft:block_entity_data`, tagged with the type's id.
use crate::block_entity_nbt::{self, canonical};
use horizon_world::nbt::{Compound, JavaString, Tag};
pub const BLOCK_ENTITY_DATA: &str = "minecraft:block_entity_data";
/// `BlockEntityTypes.OP_ONLY_CUSTOM_DATA`: the types whose data only a player
/// who can use game master blocks places (`BlockEntityType.onlyOpCanSetNbt`).
pub const OP_ONLY: [&str; 6] = [
"minecraft:command_block",
"minecraft:lectern",
"minecraft:sign",
"minecraft:hanging_sign",
"minecraft:mob_spawner",
"minecraft:trial_spawner",
];
/// The `minecraft:block_entity_data` of `stack`: its type id and its data.
pub fn data(stack: &crate::items::ItemStack) -> Option<(String, &Tag)> {
let data = stack.data()?.other(BLOCK_ENTITY_DATA)?;
Some((block_entity_nbt::id(data)?, data))
}
/// `BlockItem.shouldPrintOpWarning` for a player with game master permission:
/// the item carries data of an op-only type.
pub fn op_warning(stack: &crate::items::ItemStack) -> bool {
data(stack).is_some_and(|(id, _)| OP_ONLY.contains(&id.as_str()))
}
/// `Spawner.getSpawnEntityDisplayName` (`SpawnData.entity.id` of the item's
/// data, which `ItemStack.addDetailsToTooltip` reads for spawners and trial
/// spawners alike): the entity type a spawner item spawns.
pub fn spawner_entity(stack: &crate::items::ItemStack) -> Option<String> {
let (_, data) = data(stack)?;
match data.get("SpawnData")?.get("entity")?.get("id")? {
Tag::String(id) => Some(id.to_string_lossy()),
_ => None,
}
}
/// A part of a block entity's NBT that its item holds as a component.
#[derive(Clone, Copy)]
enum Part {
/// The NBT key and the component hold the same value.
Same(&'static str, &'static str),
/// `Items` as `minecraft:container`, in a container of this many slots.
Items(usize),
/// `LootTable` and `LootTableSeed` as `minecraft:container_loot`.
Loot,
/// `is_waxed` as `minecraft:waxed`.
Waxed,
/// A decorated pot's `item` as `minecraft:container`.
PotItem,
/// Left out of the item's data, with no component.
Drop(&'static str),
}
const NAME: Part = Part::Same("CustomName", "minecraft:custom_name");
const LOCK: Part = Part::Same("lock", "minecraft:lock");
const CONTAINER: &str = "minecraft:container";
/// Each type's `removeComponentsFromTag`, `collectImplicitComponents` and
/// `applyImplicitComponents`.
fn parts(id: &str) -> &'static [Part] {
match id {
"minecraft:chest"
| "minecraft:trapped_chest"
| "minecraft:barrel"
| "minecraft:shulker_box" => &[NAME, LOCK, Part::Items(27), Part::Loot],
"minecraft:dispenser" | "minecraft:dropper" | "minecraft:crafter" => {
&[NAME, LOCK, Part::Items(9), Part::Loot]
}
"minecraft:hopper" => &[NAME, LOCK, Part::Items(5), Part::Loot],
"minecraft:furnace" | "minecraft:smoker" | "minecraft:blast_furnace" => {
&[NAME, LOCK, Part::Items(3)]
}
"minecraft:brewing_stand" => &[NAME, LOCK, Part::Items(5)],
"minecraft:beacon" => &[NAME, LOCK],
"minecraft:enchanting_table" => &[NAME],
"minecraft:command_block" => &[NAME, Part::Drop("conditionMet"), Part::Drop("powered")],
"minecraft:campfire" => &[Part::Items(4)],
"minecraft:chiseled_bookshelf" => &[Part::Items(6)],
"minecraft:shelf" => &[Part::Items(3)],
"minecraft:beehive" => &[Part::Same("bees", "minecraft:bees")],
"minecraft:banner" => &[Part::Same("patterns", "minecraft:banner_patterns"), NAME],
"minecraft:decorated_pot" => &[
Part::Same("sherds", "minecraft:pot_decorations"),
Part::PotItem,
],
"minecraft:sign" | "minecraft:hanging_sign" => &[
Part::Same("front_text", "minecraft:sign_text_front"),
Part::Same("back_text", "minecraft:sign_text_back"),
Part::Waxed,
],
"minecraft:skull" => &[
Part::Same("profile", "minecraft:profile"),
Part::Same("note_block_sound", "minecraft:note_block_sound"),
Part::Same("custom_name", "minecraft:custom_name"),
],
_ => &[],
}
}
/// The component a part reads, and what it holds for `tag` (None: unset).
fn collect(part: Part, tag: &Tag) -> Option<(&'static str, Option<Tag>)> {
Some(match part {
Part::Same(key, component) => (
component,
tag.get(key).cloned().or_else(|| unset(component)),
),
Part::Items(_) => {
let slots = match tag.get("Items") {
Some(Tag::List(items)) => items.iter().filter_map(slot_entry).collect(),
_ => Vec::new(),
};
(CONTAINER, Some(Tag::List(slots)))
}
Part::Loot => {
let table = tag.get("LootTable").cloned();
let loot = table.map(|t| {
let mut entries = vec![("loot_table", t)];
if let Some(seed) = tag.get("LootTableSeed") {
entries.push(("seed", seed.clone()));
}
Tag::compound(entries)
});
("minecraft:container_loot", loot)
}
Part::Waxed => (
"minecraft:waxed",
matches!(tag.get("is_waxed"), Some(Tag::Byte(1)))
.then(|| Tag::Compound(Compound::new())),
),
Part::PotItem => {
let slots = match tag.get("item") {
Some(Tag::Compound(item)) => Some(container_slot(0, item.clone())),
_ => None,
};
(CONTAINER, Some(Tag::List(slots.into_iter().collect())))
}
Part::Drop(_) => return None,
})
}
/// What a type that always collects `component` gives when its NBT leaves the
/// value out (its empty value, which the NBT omits).
fn unset(component: &str) -> Option<Tag> {
Some(match component {
"minecraft:bees" | "minecraft:banner_patterns" => Tag::List(Vec::new()),
"minecraft:pot_decorations" => Tag::Compound(Compound::new()),
"minecraft:sign_text_front" | "minecraft:sign_text_back" => {
block_entity_nbt::sign_side(None)
}
_ => return None,
})
}
/// An `Items` entry as a `minecraft:container` slot.
fn slot_entry(entry: &Tag) -> Option<Tag> {
let Tag::Compound(entry) = entry else {
return None;
};
let mut item = entry.clone();
let slot = match item.remove(&JavaString::from("Slot"))? {
Tag::Byte(s) => i32::from(s),
_ => return None,
};
Some(container_slot(slot, item))
}
/// An `ItemContainerContents` slot: `ItemStackTemplate` leaves out a count of 1.
fn container_slot(slot: i32, mut item: Compound) -> Tag {
if item.get(&JavaString::from("count")) == Some(&Tag::Int(1)) {
item.remove(&JavaString::from("count"));
}
Tag::compound([("slot", Tag::Int(slot)), ("item", Tag::Compound(item))])
}
/// The value of `component` on the clone item of a type that collects it: a
/// picked item leaves it out of its patch, and a placed item without it in its
/// patch gives it to the block entity.
fn item_default(component: &str) -> Option<Tag> {
Some(match component {
CONTAINER | "minecraft:bees" | "minecraft:banner_patterns" => Tag::List(Vec::new()),
"minecraft:pot_decorations" => {
let brick = || Tag::compound([("id", Tag::String("minecraft:brick".into()))]);
Tag::compound([
("back", brick()),
("front", brick()),
("left", brick()),
("right", brick()),
])
}
"minecraft:sign_text_front" | "minecraft:sign_text_back" => {
block_entity_nbt::sign_side(None)
}
_ => return None,
})
}
const METADATA: [&str; 6] = ["id", "x", "y", "z", "keepPacked", "components"];
/// `saveCustomOnly`: the saved NBT without its id, position and components.
fn custom_only(saved: &Tag) -> Compound {
match saved {
Tag::Compound(c) => c
.iter()
.filter(|(k, _)| !METADATA.contains(&k.to_string_lossy().as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Compound::new(),
}
}
/// `addBlockDataToItem`: the component patch Ctrl + Pick Block gives the clone
/// item of the block entity saved as `saved` (a full, canonical compound).
pub fn pick(saved: &Tag) -> Compound {
let id = block_entity_nbt::id(saved).unwrap_or_default();
let mut patch = Compound::new();
// BlockItem.setBlockEntityData after removeComponentsFromTag.
let mut data = custom_only(saved);
for part in parts(&id) {
let key = match *part {
Part::Same(key, _) | Part::Drop(key) => key,
Part::Items(_) => "Items",
Part::Loot => {
data.remove(&JavaString::from("LootTableSeed"));
"LootTable"
}
Part::Waxed => "is_waxed",
Part::PotItem => "item",
};
data.remove(&JavaString::from(key));
}
if !data.is_empty() {
data.insert("id".into(), Tag::String(id.as_str().into()));
patch.insert(BLOCK_ENTITY_DATA.into(), Tag::Compound(data));
}
// ItemStack.applyComponents(collectComponents()): the block entity's own
// components, then the implicit ones; a value equal to the item's own is
// no change.
let mut collected = match saved.get("components") {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
for part in parts(&id) {
if let Some((component, value)) = collect(*part, saved) {
match value {
Some(v) => collected.insert(component.into(), v),
None => collected.remove(&JavaString::from(component)),
};
}
}
for (component, value) in collected {
if item_default(&component.to_string_lossy()).as_ref() == Some(&value) {
patch.remove(&component);
} else {
patch.insert(component, value);
}
}
patch
}
/// The block entity saved as `saved` after an item with component patch
/// `components` is placed as it: `BlockItem.updateCustomBlockEntityTag` (the
/// item's data of the same type, op-only types only when `game_master`, the
/// player can use game master blocks), then `applyComponentsFromItemStack`.
pub fn place(saved: &Tag, components: &Compound, game_master: bool) -> Tag {
let Some(id) = block_entity_nbt::id(saved) else {
return saved.clone();
};
let Tag::Compound(mut tag) = saved.clone() else {
return saved.clone();
};
// TypedEntityData.loadInto: saveCustomOnly, merge, loadCustomOnly when changed.
if let Some(Tag::Compound(data)) = components.get(&JavaString::from(BLOCK_ENTITY_DATA))
&& data
.get(&JavaString::from("id"))
.is_some_and(|t| matches!(t, Tag::String(s) if s.to_string_lossy() == id))
&& (game_master || !OP_ONLY.contains(&id.as_str()))
{
let custom = custom_only(saved);
let mut merged = custom.clone();
let mut data = data.clone();
data.remove(&JavaString::from("id"));
crate::data_cmd::merge_compound(&mut merged, &data);
if merged != custom {
for key in METADATA {
if let Some(v) = tag.get(&JavaString::from(key)) {
merged.insert(key.into(), v.clone());
}
}
if let Some(Tag::Compound(loaded)) = canonical(&Tag::Compound(merged)) {
tag = loaded;
}
}
}
// applyImplicitComponents, then the rest of the patch as the block
// entity's own components.
let mut read = vec![BLOCK_ENTITY_DATA, "minecraft:block_state"];
// The item's components: its patch over its own defaults.
let get = |c: &str| match components.get(&JavaString::from(c)) {
Some(v) => Some(v.clone()),
None if components.contains_key(&JavaString::from(format!("!{c}").as_str())) => None,
None => item_default(c),
};
let mut set = |key: &str, value: Option<Tag>| match value {
Some(v) => tag.insert(key.into(), v),
None => tag.remove(&JavaString::from(key)),
};
for part in parts(&id) {
match *part {
Part::Same(key, component) => {
read.push(component);
set(key, get(component));
}
Part::Items(size) => {
read.push(CONTAINER);
let items = container_slots(get(CONTAINER).as_ref())
.filter(|(slot, _)| (*slot as usize) < size)
.map(|(slot, mut item)| {
item.insert("Slot".into(), Tag::Byte(slot as i8));
Tag::Compound(item)
})
.collect();
set("Items", Some(Tag::List(items)));
}
Part::Loot => {
read.push("minecraft:container_loot");
if let Some(loot) = get("minecraft:container_loot") {
set("LootTable", loot.get("loot_table").cloned());
set("LootTableSeed", loot.get("seed").cloned());
}
}
Part::Waxed => {
read.push("minecraft:waxed");
set(
"is_waxed",
Some(Tag::Byte(i8::from(get("minecraft:waxed").is_some()))),
);
}
Part::PotItem => {
read.push(CONTAINER);
let first = container_slots(get(CONTAINER).as_ref()).find(|(slot, _)| *slot == 0);
set("item", first.map(|(_, item)| Tag::Compound(item)));
}
Part::Drop(_) => {}
}
}
let own: Compound = components
.iter()
.filter(|(k, _)| {
let k = k.to_string_lossy();
!k.starts_with('!') && !read.contains(&k.as_str())
})
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
tag.insert("components".into(), Tag::Compound(own));
let tag = Tag::Compound(tag);
canonical(&tag).unwrap_or(tag)
}
/// The slots of a `minecraft:container` component.
fn container_slots(container: Option<&Tag>) -> impl Iterator<Item = (i32, Compound)> + '_ {
let list = match container {
Some(Tag::List(list)) => list.as_slice(),
_ => &[],
};
list.iter().filter_map(|entry| {
let slot = match entry.get("slot")? {
Tag::Int(s) => *s,
_ => return None,
};
match entry.get("item")? {
Tag::Compound(item) => Some((slot, item.clone())),
_ => None,
}
})
}
#[cfg(test)]
mod tests {
use super::*;
fn snbt(text: &str) -> Tag {
horizon_world::nbt::parse_snbt(text).expect("snbt").0
}
fn saved(text: &str) -> Tag {
canonical(&snbt(text)).expect("known type")
}
fn canon(patch: &Compound) -> String {
crate::item_data::canon_tag(&Tag::Compound(patch.clone()))
}
#[test]
fn a_filled_named_chest_gives_its_items_and_name_as_components() {
let chest = saved(
"{id:\"minecraft:chest\",x:1,y:2,z:3,CustomName:\"Loot\",\
Items:[{Slot:4b,id:\"minecraft:stone\",count:5}]}",
);
let patch = pick(&chest);
assert_eq!(
canon(&patch),
crate::item_data::canon_tag(&snbt(
"{\"minecraft:container\":[{slot:4,item:{id:\"minecraft:stone\",count:5}}],\
\"minecraft:custom_name\":\"Loot\"}"
))
);
// Placing it back gives the same chest.
let empty = saved("{id:\"minecraft:chest\",x:1,y:2,z:3}");
assert_eq!(place(&empty, &patch, false), chest);
// An empty chest has nothing to carry.
assert!(pick(&empty).is_empty());
}
#[test]
fn a_command_block_keeps_its_command_in_block_entity_data() {
let block = saved(
"{id:\"minecraft:command_block\",x:0,y:0,z:0,Command:\"say hi\",auto:1b,powered:1b}",
);
let patch = pick(&block);
let data = patch
.get(&JavaString::from(BLOCK_ENTITY_DATA))
.expect("data");
assert_eq!(data.get("Command"), Some(&Tag::String("say hi".into())));
assert_eq!(data.get("powered"), None);
assert_eq!(
data.get("id"),
Some(&Tag::String("minecraft:command_block".into()))
);
// Only a player who can use game master blocks places it.
let fresh = saved("{id:\"minecraft:command_block\",x:0,y:0,z:0}");
assert_eq!(place(&fresh, &patch, false), fresh);
assert_eq!(
place(&fresh, &patch, true).get("Command"),
Some(&Tag::String("say hi".into()))
);
// Data of another type is ignored.
let chest = saved("{id:\"minecraft:chest\",x:0,y:0,z:0}");
assert_eq!(place(&chest, &patch, true), chest);
}
#[test]
fn item_data_names_its_spawn_and_op_only_types() {
let item = |text: &str| {
let components = snbt(&format!("{{\"minecraft:block_entity_data\":{text}}}"));
let (damage, extra) = crate::item_data::decode_components(Some(&components));
crate::items::ItemStack {
damage,
extra,
..crate::items::ItemStack::new("minecraft:spawner", 1)
}
};
let spawner =
item("{id:\"minecraft:mob_spawner\",SpawnData:{entity:{id:\"minecraft:zombie\"}}}");
assert_eq!(
spawner_entity(&spawner).as_deref(),
Some("minecraft:zombie")
);
assert!(op_warning(&spawner));
let chest = item("{id:\"minecraft:chest\",LootTable:\"x\"}");
assert_eq!(spawner_entity(&chest), None);
assert!(!op_warning(&chest));
}
#[test]
fn a_written_sign_gives_its_text_and_wax() {
let sign = saved(
"{id:\"minecraft:sign\",x:0,y:0,z:0,is_waxed:1b,\
front_text:{messages:[\"a\",\"b\",\"\",\"\"]}}",
);
let patch = pick(&sign);
let keys: Vec<String> = patch.keys().map(|k| k.to_string_lossy()).collect();
assert_eq!(keys, ["minecraft:sign_text_front", "minecraft:waxed"]);
let fresh = saved("{id:\"minecraft:sign\",x:0,y:0,z:0}");
assert_eq!(place(&fresh, &patch, false), sign);
}
}
@@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool {
matches!(tag, Tag::IntArray(v) if v.len() == 3)
}
/// The loaded `SignText` of one side, or the empty text.
fn sign_side(tag: Option<&Tag>) -> Tag {
pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag {
let empty = || string("");
let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) {
Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
+67
View File
@@ -163,3 +163,70 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
);
}
}
#[test]
fn history_arrows_recall_messages_and_restore_the_draft() {
use winit::keyboard::KeyCode::{ArrowDown, ArrowUp};
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let commands = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
let history = vec!["first message".to_owned(), "latest message".to_owned()];
let mut screen = ChatScreen::new(&m, &commands, "unfinished draft", history.len(), 640, 360);
for (key, expected) in [
(ArrowUp, "latest message"),
(ArrowUp, "first message"),
(ArrowUp, "first message"),
(ArrowDown, "latest message"),
(ArrowDown, "unfinished draft"),
(ArrowDown, "unfinished draft"),
] {
assert_eq!(
screen.key(&m, &commands, &history, key, false, false),
ChatAction::None
);
assert_eq!(screen.value(), expected);
}
}
#[test]
fn mod_commands_are_coloured_and_complete_like_vanilla_ones() {
let font = font();
let m = Measure(&font);
// Allow Commands off: a mod's command needs no level.
let registries = Registries::default();
let vanilla = crate::command::vanilla::game_dispatcher();
let modded = vanilla.with_mod_commands(["where", "coords"]);
let red = |screen: &ChatScreen| {
screen
.format(screen.value(), 0)
.spans
.iter()
.any(|s| s.style.color == Some(text::RED))
};
let typed = |dispatcher: &crate::command::Dispatcher, line: &str| {
let c = Commands {
dispatcher,
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
screen.type_text(&m, &c, line);
screen
};
// Unknown without the mod's tree (#456).
assert!(red(&typed(vanilla, "/coords")));
for line in ["/coords", "/where", "/where me and you"] {
assert!(!red(&typed(&modded, line)), "{line}");
}
let c = Commands {
dispatcher: &modded,
registries: &registries,
};
let mut screen = typed(&modded, "/coo");
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false);
assert_eq!(screen.value(), "/coords");
}
+217
View File
@@ -68,9 +68,226 @@ pub fn cells(radius: i32) -> impl Iterator<Item = (i32, i32)> {
})
}
/// Per-frame cloud inputs. Resources are immutable for the renderer's lifetime:
/// resource-pack reloads replace the renderer and its cache together.
pub struct Input<'a> {
pub texture: &'a (u32, u32, Vec<bool>),
pub uv: [f32; 2],
pub camera: glam::DVec3,
pub time: i64,
pub partial_tick: f64,
pub range: i32,
pub fast: bool,
pub color: [f32; 4],
}
#[derive(Debug, PartialEq, Eq)]
struct MeshKey {
cell_x: i64,
cell_z: i64,
radius: i32,
fast: bool,
// The two vertical face tests include both surfaces at the boundaries.
top: bool,
bottom: bool,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct Uniform {
offset: [f32; 4],
colors: [[f32; 4]; 4],
}
impl Input<'_> {
fn state(&self) -> (MeshKey, Uniform) {
let (w, h, _) = self.texture;
let offset = self.time.rem_euclid(i64::from(*w) * 400) as f64 + self.partial_tick;
let mut x = self.camera.x + offset * 0.030_000_001;
let mut z = self.camera.z + 3.96;
let (tw, th) = (f64::from(*w) * 12.0, f64::from(*h) * 12.0);
x -= (x / tw).floor() * tw;
z -= (z / th).floor() * th;
let cell_x = (x / 12.0).floor() as i64;
let cell_z = (z / 12.0).floor() as i64;
let bottom = (192.33 - self.camera.y) as f32;
let key = MeshKey {
cell_x,
cell_z,
radius: radius_cells(self.range),
fast: self.fast,
top: bottom <= 0.0,
bottom: bottom + 4.0 >= 0.0,
};
let colors = [1.0, 0.7, 0.8, 0.9].map(|shade| {
let [r, g, b, a] = self.color;
[r * shade, g * shade, b * shade, a]
.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0)
});
(
key,
Uniform {
offset: [
-(x - cell_x as f64 * 12.0) as f32,
bottom,
-(z - cell_z as f64 * 12.0) as f32,
0.0,
],
colors,
},
)
}
}
#[derive(Default)]
pub(crate) struct Mesh {
key: Option<MeshKey>,
pub vertices: Vec<crate::mesher::Vertex>,
}
impl Mesh {
/// Returns true only when vertices must be uploaded. Sub-cell motion and
/// color changes update only the uniform, as in CloudRenderer.prepare.
pub fn prepare(&mut self, input: &Input<'_>) -> (bool, Uniform) {
let (key, uniform) = input.state();
if self.key.as_ref() == Some(&key) {
return (false, uniform);
}
self.vertices.clear();
let (w, h, cells) = input.texture;
let (w, h) = (i64::from(*w), i64::from(*h));
let (cell_x, cell_z, radius) = (key.cell_x, key.cell_z, key.radius);
let bottom = uniform.offset[1];
let uv = input.uv;
let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize];
for (dx, dz) in self::cells(radius) {
let (dx, dz) = (i64::from(dx), i64::from(dz));
let (cx, cz) = (cell_x + dx, cell_z + dz);
if !filled(cx, cz) {
continue;
}
let x0 = dx as f32 * 12.0;
let z0 = dz as f32 * 12.0;
let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, 0.0, 4.0);
let mut quad = |p: [[f32; 3]; 4], shade: u32| {
for v in p {
// Overlay 4: clouds (unlit, faded by the cloud fog end).
self.vertices.push(crate::mesher::Vertex {
normal: [0; 4],
pos: v,
uv,
layer: 4,
color: u32::MAX,
light: shade,
});
}
};
if input.fast {
for p in flat_cell(x0, z0, 0.0) {
quad(p, 0);
}
continue;
}
let quads = [
([[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]], 1),
([[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], 0),
([[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], 2),
([[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], 2),
([[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], 3),
([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], 3),
];
let mask = face_mask(
dx as i32,
dz as i32,
bottom,
[
!filled(cx, cz - 1),
!filled(cx, cz + 1),
!filled(cx - 1, cz),
!filled(cx + 1, cz),
],
);
for (direction, inside) in faces(mask) {
let (p, shade) = quads[usize::from(direction)];
quad(if inside { [p[3], p[2], p[1], p[0]] } else { p }, shade);
}
}
self.key = Some(key);
(true, uniform)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cached_mesh_tracks_geometry_but_not_subcell_motion_or_color() {
let texture = (8, 8, (0..64).map(|i| i % 3 != 0).collect());
let mut input = Input {
texture: &texture,
uv: [0.5; 2],
camera: glam::DVec3::new(1.0, 100.0, 1.0),
time: 0,
partial_tick: 0.0,
range: 2,
fast: false,
color: [1.0; 4],
};
let mut mesh = Mesh::default();
assert!(mesh.prepare(&input).0);
let vertices = bytemuck::cast_slice::<_, u8>(&mesh.vertices).to_vec();
let pointer = mesh.vertices.as_ptr();
for tick in 0..100 {
input.time = tick;
input.partial_tick = 0.5;
input.camera.x = 2.0;
input.camera.y = 101.0;
input.color = [0.8, 0.7, 0.6, 0.5];
let (rebuilt, uniform) = mesh.prepare(&input);
assert!(!rebuilt);
assert_eq!(mesh.vertices.as_ptr(), pointer);
assert_eq!(bytemuck::cast_slice::<_, u8>(&mesh.vertices), vertices);
assert_eq!(uniform.offset[1], (192.33 - input.camera.y) as f32);
assert_eq!(
uniform.colors[1],
[0.8 * 0.7, 0.7 * 0.7, 0.6 * 0.7, 0.5].map(|v| (v * 255.0) as u8 as f32 / 255.0)
);
for color in uniform.colors {
assert_eq!(color[3], 127.0 / 255.0);
}
}
for (x, y, z, range, fast) in [
(13.0, 101.0, 1.0, 2, false),
(13.0, 101.0, -5.0, 2, false),
(13.0, 192.33, -5.0, 2, false),
(13.0, 196.34, -5.0, 2, false),
(13.0, 196.34, -5.0, 3, false),
(13.0, 196.34, -5.0, 3, true),
] {
input.camera = glam::DVec3::new(x, y, z);
input.range = range;
input.fast = fast;
assert!(mesh.prepare(&input).0);
let mut fresh = Mesh::default();
fresh.prepare(&input);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&mesh.vertices),
bytemuck::cast_slice::<_, u8>(&fresh.vertices)
);
assert!(!mesh.prepare(&input).0);
}
// Drift alone crosses a cell, even with a stationary camera.
input.time += 400;
assert!(mesh.prepare(&input).0);
// Resource reload constructs a new renderer and cache, including empty packs.
let mut reloaded = Mesh::default();
let empty = (1, 1, vec![false]);
input.texture = &empty;
assert!(reloaded.prepare(&input).0);
assert!(reloaded.vertices.is_empty());
assert!(!reloaded.prepare(&input).0);
}
#[test]
fn settings_and_packed_alpha_gate_clouds() {
for mode in ["false", "fast", "true"] {
+74 -11
View File
@@ -65,6 +65,68 @@ pub struct SceneCollisions<'w, 'r> {
/// The entity colliding, for powder snow; None: no fall, no boots.
pub subject: Option<PowderSnowSubject>,
}
/// Already selected entity boxes alongside the resident block collision world.
pub struct EntityCollisions<'a, W> {
pub blocks: W,
pub entities: &'a [Aabb],
}
impl<W: BlockCollisionWorld> BlockCollisionWorld for EntityCollisions<'_, W> {
type Error = W::Error;
type Chunk = W::Chunk;
fn collision_chunk(
&mut self,
p: ChunkPos,
) -> std::result::Result<Option<Self::Chunk>, Self::Error> {
self.blocks.collision_chunk(p)
}
fn collision_block(
&mut self,
chunk: Self::Chunk,
p: BlockPos,
) -> std::result::Result<CollisionBlock, Self::Error> {
self.blocks.collision_block(chunk, p)
}
fn is_suffocating(
&mut self,
chunk: Self::Chunk,
block: CollisionBlock,
p: BlockPos,
) -> std::result::Result<bool, Self::Error> {
self.blocks.is_suffocating(chunk, block, p)
}
fn context_shape(
&mut self,
block: CollisionBlock,
p: BlockPos,
context: &CollisionContext<'_>,
) -> std::result::Result<VoxelShape, Self::Error> {
self.blocks.context_shape(block, p, context)
}
}
impl<W: EntityMovementWorld<Error = io::Error>> EntityMovementWorld for EntityCollisions<'_, W> {
type Error = io::Error;
fn entity_collisions(
&mut self,
entity: EntityIdentity,
bounds: Aabb,
) -> io::Result<Vec<VoxelShape>> {
let mut shapes = self.blocks.entity_collisions(entity, bounds)?;
for &aabb in self.entities {
// EntityGetter.getEntityCollisions expands its entity query by 1e-7.
if aabb.intersects(bounds.inflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7))) {
shapes.push(VoxelShape::from_box(aabb).map_err(io::Error::other)?);
}
}
Ok(shapes)
}
fn movement_border(
&mut self,
entity: EntityIdentity,
bounds: Aabb,
) -> io::Result<Option<VoxelShape>> {
self.blocks.movement_border(entity, bounds)
}
}
impl SceneCollisions<'_, '_> {
/// Position contexts permit geometric movement probes without inventing a
/// player, inventory, effects or fluid-standing behavior; a lava walker
@@ -147,21 +209,22 @@ where
)
.unwrap_or(false)
}
impl BlockCollisionWorld for SceneCollisions<'_, '_> {
impl<'w> BlockCollisionWorld for SceneCollisions<'w, '_> {
type Error = io::Error;
type Chunk = ChunkPos;
fn collision_chunk(&mut self, p: ChunkPos) -> io::Result<Option<ChunkPos>> {
Ok(self.world.chunks.contains_key(&(p.x, p.z)).then_some(p))
/// The resident column, looked up once per chunk the scan enters.
type Chunk = &'w crate::chunk::Chunk;
fn collision_chunk(&mut self, p: ChunkPos) -> io::Result<Option<Self::Chunk>> {
Ok(self.world.chunks.get(&(p.x, p.z)).map(|chunk| &**chunk))
}
fn collision_block(&mut self, chunk: ChunkPos, p: BlockPos) -> io::Result<CollisionBlock> {
let chunk = self
.world
.chunks
.get(&(chunk.x, chunk.z))
.ok_or_else(|| io::Error::other("resident collision chunk disappeared"))?;
fn collision_block(&mut self, chunk: Self::Chunk, p: BlockPos) -> io::Result<CollisionBlock> {
self.binding.collision_block(chunk.block(p.x, p.y, p.z))
}
fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result<bool> {
fn is_suffocating(
&mut self,
_: Self::Chunk,
_: CollisionBlock,
_: BlockPos,
) -> io::Result<bool> {
Ok(false)
}
fn context_shape(
+50
View File
@@ -61,6 +61,33 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> {
_ => Err(not_map(t)),
},
"minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t),
// TypedEntityData.codec: the type is the compound's id.
"minecraft:block_entity_data" => match t {
Tag::Compound(c) => match c.get(&"id".into()) {
None => Err(format!("Expected 'id' field in {}", snbt(t))),
Some(Tag::String(id)) => {
let id = id.to_string_lossy();
let id = if id.contains(':') {
id
} else {
format!("minecraft:{id}")
};
let known = crate::block_entity_nbt::TYPES
.iter()
.chain(&crate::block_entity_nbt::NEWEST)
.any(|k| *k == id);
if known {
Ok(())
} else {
Err(format!(
"Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: {id}"
))
}
}
Some(_) => Ok(()),
},
_ => Ok(()),
},
_ => Ok(()),
}
}
@@ -609,3 +636,26 @@ pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
fn _unused(t: &Tag) -> String {
snbt(t)
}
#[cfg(test)]
mod tests {
use super::decode_component;
fn check(snbt: &str) -> Result<(), String> {
let tag = horizon_world::nbt::parse_snbt(snbt).expect("snbt").0;
decode_component("minecraft:block_entity_data", &tag)
}
#[test]
fn block_entity_data_needs_a_known_type() {
assert_eq!(check("{id:\"chest\",Lock:1}"), Ok(()));
assert_eq!(
check("{Command:\"say\"}"),
Err("Expected 'id' field in {Command:\"say\"}".into())
);
assert_eq!(
check("{id:\"minecraft:stone\"}"),
Err("Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: minecraft:stone".into())
);
}
}
+16
View File
@@ -23,6 +23,9 @@ mod vanilla_order;
use crate::text::Text;
pub use args::{Arg, ArgType, Registries};
/// The command id of a mod's command (`Dispatcher::with_mod_commands`).
pub const MOD_COMMAND: &str = "mod";
/// A command error (CommandSyntaxException): the message and, for parse
/// errors, the input and cursor it occurred at.
#[derive(Clone, Debug, PartialEq)]
@@ -770,6 +773,19 @@ impl Dispatcher {
self.nodes[node].permission = level;
node
}
/// This tree plus the commands mods own (`docs/mods.md`), so the chat
/// colours and completes them like the others. Every player may use one,
/// and the text after its name goes to the mod as it was typed.
pub fn with_mod_commands<'a>(&self, names: impl IntoIterator<Item = &'a str>) -> Dispatcher {
let mut d = self.clone();
for name in names {
let command = d.literal(0, name);
d.executes(command, MOD_COMMAND);
let args = d.argument(command, "args", ArgType::Greedy);
d.executes(args, MOD_COMMAND);
}
d
}
/// A root literal by name.
pub fn find(&self, name: &str) -> Option<usize> {
self.nodes[0]
@@ -570,3 +570,25 @@ fn place_template_tree() {
assert!(run("place template minecraft:x ~ ~ ~ sideways").is_err());
assert!(run("place template minecraft:x ~ ~ ~ none none 2").is_err());
}
#[test]
fn mod_commands_join_the_tree_for_every_player() {
let reg = Registries {
permission: 0,
..reg()
};
let d = vanilla::game_dispatcher().with_mod_commands(["where"]);
for line in ["where", "where north 12"] {
let parse = d.parse(line, &reg);
assert_eq!(parse.executable().unwrap().1, MOD_COMMAND, "{line}");
}
let parse = d.parse("w", &reg);
let names: Vec<String> = d
.client_suggestions(&parse, 1, &reg)
.1
.into_iter()
.map(|s| s.text)
.collect();
assert!(names.contains(&"where".to_owned()), "{names:?}");
// The game's own tree is left as it was.
assert!(vanilla::game_dispatcher().find("where").is_none());
}
+256
View File
@@ -0,0 +1,256 @@
//! `CommandBlockEntity` with its `BaseCommandBlock`: the command, the success
//! count comparators read, the output it keeps, and the powered, automatic
//! and condition flags `CommandBlock.tick` runs on.
use crate::{
save::{number, text},
text::Text,
};
use horizon_world::nbt::Tag;
/// `CommandBlockEntity.Mode`, in declaration order (the edit screen's mode
/// button cycles through it).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
Sequence,
Auto,
Redstone,
}
impl Mode {
/// `CommandBlockEntity.getMode`: the block the entity sits in.
pub fn of_block(name: &str) -> Option<Self> {
match name {
"minecraft:command_block" => Some(Self::Redstone),
"minecraft:repeating_command_block" => Some(Self::Auto),
"minecraft:chain_command_block" => Some(Self::Sequence),
_ => None,
}
}
/// The block `ServerGamePacketListenerImpl.handleSetCommandBlock` puts
/// down for a mode.
pub fn block(self) -> &'static str {
match self {
Self::Sequence => "minecraft:chain_command_block",
Self::Auto => "minecraft:repeating_command_block",
Self::Redstone => "minecraft:command_block",
}
}
/// `CycleButton`: the next value, wrapping round.
pub fn next(self) -> Self {
match self {
Self::Sequence => Self::Auto,
Self::Auto => Self::Redstone,
Self::Redstone => Self::Sequence,
}
}
/// `CommandBlockEditScreen`'s label for the mode.
pub fn label(self) -> &'static str {
match self {
Self::Sequence => "advMode.mode.sequence",
Self::Auto => "advMode.mode.auto",
Self::Redstone => "advMode.mode.redstone",
}
}
}
/// The `automatic` flag `CommandBlock` gives its entity: chain command blocks
/// are always active when placed.
pub fn automatic_block(name: &str) -> bool {
name == "minecraft:chain_command_block"
}
#[derive(Clone, Debug, PartialEq)]
pub struct CommandBlock {
pub command: String,
pub success_count: i32,
/// `CustomName` as saved (a text component).
pub custom_name: Option<Tag>,
pub track_output: bool,
pub last_output: Option<Text>,
pub update_last_execution: bool,
/// The game time of the last run, -1 for none.
pub last_execution: i64,
pub powered: bool,
pub auto: bool,
pub condition_met: bool,
}
impl Default for CommandBlock {
fn default() -> Self {
Self {
command: String::new(),
success_count: 0,
custom_name: None,
track_output: true,
last_output: None,
update_last_execution: true,
last_execution: -1,
powered: false,
auto: false,
condition_met: false,
}
}
}
impl CommandBlock {
/// `CommandBlockEntity.loadAdditional` with `BaseCommandBlock.load`.
pub fn load(tag: &Tag) -> Self {
let flag = |key: &str, default: bool| number(tag.get(key)).map_or(default, |v| v != 0);
let track_output = flag("TrackOutput", true);
let update_last_execution = flag("UpdateLastExecution", true);
Self {
command: text(tag.get("Command")).unwrap_or_default(),
success_count: number(tag.get("SuccessCount")).unwrap_or(0) as i32,
custom_name: tag.get("CustomName").cloned(),
track_output,
last_output: track_output
.then(|| tag.get("LastOutput"))
.flatten()
.map(|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))),
update_last_execution,
last_execution: if update_last_execution {
number(tag.get("LastExecution")).unwrap_or(-1)
} else {
-1
},
powered: flag("powered", false),
auto: flag("auto", false),
condition_met: flag("conditionMet", false),
}
}
/// `CommandBlockEntity.saveAdditional`. The last output is written as a
/// plain string component.
pub fn save(&self) -> Vec<(&'static str, Tag)> {
let mut out = vec![
("Command", Tag::String(self.command.as_str().into())),
("SuccessCount", Tag::Int(self.success_count)),
];
if let Some(name) = &self.custom_name {
out.push(("CustomName", name.clone()));
}
out.push(("TrackOutput", Tag::Byte(i8::from(self.track_output))));
if self.track_output
&& let Some(last) = &self.last_output
{
out.push(("LastOutput", Tag::String(last.plain().as_str().into())));
}
out.push((
"UpdateLastExecution",
Tag::Byte(i8::from(self.update_last_execution)),
));
if self.update_last_execution && self.last_execution != -1 {
out.push(("LastExecution", Tag::Long(self.last_execution)));
}
out.push(("powered", Tag::Byte(i8::from(self.powered))));
out.push(("conditionMet", Tag::Byte(i8::from(self.condition_met))));
out.push(("auto", Tag::Byte(i8::from(self.auto))));
out
}
/// `BaseCommandBlock.setCommand`: a new command starts at no successes.
pub fn set_command(&mut self, command: &str) {
self.command = command.to_owned();
self.success_count = 0;
}
/// `getLastOutput().getString()`: what the edit screen shows.
pub fn last_output_string(&self) -> String {
self.last_output
.as_ref()
.map(Text::plain)
.unwrap_or_default()
}
/// `getName`: the custom name, else `@`.
pub fn name(&self) -> Text {
self.custom_name.as_ref().map_or_else(
|| Text::literal("@"),
|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
)
}
}
/// What `CommandBlock.tick` does with a block of `mode` whose condition was
/// `met` when last checked: run its command (`Some(true)`), clear the success
/// count of a conditional block (`Some(false)`), or nothing. Chain blocks
/// only run from the block before them (`executeChain`).
pub fn tick_action(mode: Mode, met: bool, conditional: bool) -> Option<bool> {
match mode {
Mode::Sequence => None,
_ if met => Some(true),
_ if conditional => Some(false),
_ => None,
}
}
/// `CommandBlock.tick`: a repeating block ticks again next tick while powered
/// or always active.
pub fn repeats(mode: Mode, powered: bool, auto: bool) -> bool {
mode == Mode::Auto && (powered || auto)
}
/// `CommandBlock.setPoweredAndUpdate`: a rising signal schedules the impulse
/// or repeating block's tick unless it is always active anyway.
pub fn power_schedules(mode: Mode, was_powered: bool, powered: bool, auto: bool) -> bool {
powered && !was_powered && !auto && mode != Mode::Sequence
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn modes_cycle_and_map_to_blocks() {
for mode in [Mode::Sequence, Mode::Auto, Mode::Redstone] {
assert_eq!(Mode::of_block(mode.block()), Some(mode));
}
assert_eq!(Mode::Redstone.next(), Mode::Sequence);
assert_eq!(Mode::Sequence.next(), Mode::Auto);
assert!(automatic_block("minecraft:chain_command_block"));
assert!(!automatic_block("minecraft:repeating_command_block"));
}
#[test]
fn tick_follows_the_condition() {
assert_eq!(tick_action(Mode::Redstone, true, false), Some(true));
assert_eq!(tick_action(Mode::Redstone, false, true), Some(false));
assert_eq!(tick_action(Mode::Auto, false, false), None);
assert_eq!(tick_action(Mode::Sequence, true, false), None);
assert!(repeats(Mode::Auto, false, true));
assert!(!repeats(Mode::Auto, false, false));
assert!(!repeats(Mode::Redstone, true, true));
}
#[test]
fn only_a_rising_edge_schedules() {
assert!(power_schedules(Mode::Redstone, false, true, false));
assert!(!power_schedules(Mode::Redstone, true, true, false));
assert!(!power_schedules(Mode::Redstone, false, true, true));
assert!(!power_schedules(Mode::Sequence, false, true, false));
}
#[test]
fn saves_like_base_command_block() {
let block = CommandBlock {
command: "say hi".into(),
success_count: 1,
last_output: Some(Text::literal("[12:00:00] hi")),
last_execution: 42,
powered: true,
..CommandBlock::default()
};
let tag = Tag::compound(block.save());
let back = CommandBlock::load(&tag);
assert_eq!(back.command, "say hi");
assert_eq!(back.success_count, 1);
assert_eq!(back.last_output_string(), "[12:00:00] hi");
assert_eq!(back.last_execution, 42);
assert!(back.powered && !back.auto && back.track_output);
// Not tracking output drops it, and no execution time is kept at -1.
let quiet = CommandBlock {
track_output: false,
last_output: Some(Text::literal("x")),
..CommandBlock::default()
};
let tag = Tag::compound(quiet.save());
assert!(tag.get("LastOutput").is_none() && tag.get("LastExecution").is_none());
assert_eq!(CommandBlock::load(&tag).last_output, None);
}
}
+27 -3
View File
@@ -70,8 +70,12 @@ pub enum BlockEntity {
Spawner(Box<crate::mobs::spawner::Spawner>),
/// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`).
TrialSpawner(Box<crate::mobs::trial_spawner::TrialSpawner>),
/// `VaultBlockEntity` (`crate::vault`).
Vault(Box<crate::vault::Vault>),
/// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`).
Beehive(Box<crate::beehive::Beehive>),
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
CommandBlock(Box<crate::command_block::CommandBlock>),
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
@@ -192,12 +196,24 @@ impl BlockEntity {
if name == "minecraft:trial_spawner" {
return Some(Self::TrialSpawner(Box::default()));
}
if name == "minecraft:vault" {
return Some(Self::Vault(Box::default()));
}
if name == "minecraft:beehive" || name == "minecraft:bee_nest" {
return Some(Self::Beehive(Box::default()));
}
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
if crate::command_block::Mode::of_block(name).is_some() {
// CommandBlock.newBlockEntity: setAutomatic(this.automatic).
return Some(Self::CommandBlock(Box::new(
crate::command_block::CommandBlock {
auto: crate::command_block::automatic_block(name),
..Default::default()
},
)));
}
if let Some(sculk) = crate::sculk::SculkEntity::for_block(name) {
return Some(Self::Sculk(Box::new(sculk)));
}
@@ -272,7 +288,9 @@ impl BlockEntity {
Self::CreakingHeart(_) => "minecraft:creaking_heart",
Self::Spawner(_) => "minecraft:mob_spawner",
Self::TrialSpawner(_) => "minecraft:trial_spawner",
Self::Vault(_) => "minecraft:vault",
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -286,7 +304,9 @@ impl BlockEntity {
| Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Beehive(_) => Vec::new(),
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -308,7 +328,9 @@ impl BlockEntity {
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Beehive(_) => &[],
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -326,7 +348,9 @@ impl BlockEntity {
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Beehive(_) => &mut [],
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => &mut [],
}
}
}
+12 -8
View File
@@ -467,13 +467,16 @@ impl FrameStats {
}
let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum();
let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1];
// Average frame time of the slowest 1% of frames, as frames per second.
let slowest = n.div_ceil(100);
let slow: f64 = sorted[n - slowest..]
.iter()
.map(|&m| f64::from(m))
.sum::<f64>()
/ slowest as f64;
// Average frame time of the slowest 1% (0.1%) of frames, as frames per second.
let low = |per: usize| {
let slowest = n.div_ceil(per);
let slow: f64 = sorted[n - slowest..]
.iter()
.map(|&m| f64::from(m))
.sum::<f64>()
/ slowest as f64;
1000.0 / slow
};
// Where the slowest 1% of frames by CPU time go.
let slow_phases = {
let mut cpu = self.cpu.clone();
@@ -487,7 +490,8 @@ impl FrameStats {
"frames": n,
"seconds": total / 1000.0,
"avg_fps": n as f64 * 1000.0 / total,
"low_1pct_fps": 1000.0 / slow,
"low_1pct_fps": low(100),
"low_01pct_fps": low(1000),
"p50_ms": percentile(0.5),
"p95_ms": percentile(0.95),
"p99_ms": percentile(0.99),
+27 -12
View File
@@ -14,7 +14,7 @@ use serde_json::Value;
use std::{
collections::{HashMap, HashSet},
fs,
path::Path,
path::{Path, PathBuf},
sync::Arc,
};
@@ -1182,18 +1182,33 @@ impl Recipes {
let mut crafting = Vec::new();
let mut cooking = Vec::new();
let mut meta = HashMap::new();
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
let json_files = |dir: &Path| -> Result<Vec<PathBuf>> {
let mut files: Vec<_> = fs::read_dir(dir)?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
files.sort();
Ok(files)
};
// Vanilla's recipes by bare name, then content mods' as `<ns>:<name>`.
let mut files: Vec<(String, PathBuf)> = json_files(&root.join("data/minecraft/recipe"))?
.into_iter()
.map(|p| (String::new(), p))
.collect();
files.sort();
for path in files {
let name = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_owned();
for namespace in crate::mod_content::namespaces(root) {
let dir = root.join(format!("data/{namespace}/recipe"));
if dir.is_dir() {
files.extend(
json_files(&dir)?
.into_iter()
.map(|p| (format!("{namespace}:"), p)),
);
}
}
for (prefix, path) in files {
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
let name = format!("{prefix}{stem}");
let v: Value = serde_json::from_slice(&fs::read(&path)?)?;
let text = |k: &str| v[k].as_str().unwrap_or("").to_owned();
meta.insert(name.clone(), (text("category"), text("group")));
+14 -7
View File
@@ -49,17 +49,24 @@ pub struct Names {
}
impl Names {
pub fn load(root: &Path) -> Self {
let map = fs::read(root.join("assets/minecraft/lang/en_us.json"))
.ok()
.and_then(|b| serde_json::from_slice::<HashMap<String, String>>(&b).ok())
.unwrap_or_default();
let read = |namespace: &str| {
fs::read(root.join(format!("assets/{namespace}/lang/en_us.json")))
.ok()
.and_then(|b| serde_json::from_slice::<HashMap<String, String>>(&b).ok())
.unwrap_or_default()
};
let mut map = read("minecraft");
// Content mods' names (docs/modpacks.md); none in a vanilla root.
for namespace in crate::mod_content::namespaces(root) {
map.extend(read(&namespace));
}
Self { map }
}
pub fn item(&self, id: &str) -> String {
let path = id.trim_start_matches("minecraft:");
let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id));
self.map
.get(&format!("item.minecraft.{path}"))
.or_else(|| self.map.get(&format!("block.minecraft.{path}")))
.get(&format!("item.{namespace}.{path}"))
.or_else(|| self.map.get(&format!("block.{namespace}.{path}")))
.cloned()
.unwrap_or_else(|| path.replace('_', " "))
}
+62 -1
View File
@@ -34,6 +34,27 @@ impl DataPack {
}
}
}
/// The files of `data/<namespace>/<kind>/` for each kind, in the order
/// `list("data/")` gives them. A folder pack walks only those folders:
/// the built-in pack holds about 10,000 other data files.
fn list_kinds(&self, kinds: &[&str]) -> Vec<String> {
debug_assert!(kinds.is_sorted(), "kinds in walk order");
let Source::Dir(root) = &self.source else {
return self.list("data/");
};
let Ok(entries) = std::fs::read_dir(root.join("data")) else {
return Vec::new();
};
let mut namespaces: Vec<_> = entries.flatten().map(|e| e.path()).collect();
namespaces.sort();
let mut out = Vec::new();
for ns in namespaces {
for kind in kinds {
walk(root, &ns.join(kind), &mut out);
}
}
out
}
fn read(&self, path: &str) -> Option<Vec<u8>> {
match &self.source {
Source::Zip(z) => z.read(path).ok(),
@@ -308,7 +329,7 @@ impl DataStore {
pub fn load(packs: &[&DataPack]) -> Self {
let mut s = Self::default();
for pack in packs {
for f in pack.list("data/") {
for f in pack.list_kinds(&["function", "item_modifier", "predicate", "tags/function"]) {
if let Some(id) = resource_id(&f, "function", ".mcfunction")
&& let Some(bytes) = pack.read(&f)
{
@@ -505,4 +526,44 @@ mod tests {
assert!(store.predicates.contains_key("mine:p"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn folder_packs_list_the_needed_kinds_in_walk_order() {
let dir = std::env::temp_dir().join(format!("hz-datapack-kinds-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let pack = dir.join("datapacks/p");
let files = [
"data/b/function/z.mcfunction",
"data/b/function/a/y.mcfunction",
"data/b/loot_table/l.json",
"data/b/tags/block/t.json",
"data/b/tags/function/load.json",
"data/b/predicate/p.json",
"data/a/item_modifier/m.json",
"data/a/function/f.mcfunction",
"data/a/functions/old.mcfunction",
"data/a/recipe/r.json",
"data/a/tags/function/tick.json",
"data/c/worldgen/noise/n.json",
];
for f in files {
let path = pack.join(f);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "{}").unwrap();
}
std::fs::write(pack.join("pack.mcmeta"), "{}").unwrap();
let p = DataPack::builtin(&pack);
let kinds = ["function", "item_modifier", "predicate", "tags/function"];
let wanted: Vec<String> = p
.list("data/")
.into_iter()
.filter(|f| {
let rest = f.splitn(3, '/').nth(2).unwrap_or_default();
kinds.iter().any(|k| rest.starts_with(&format!("{k}/")))
})
.collect();
assert_eq!(wanted.len(), 7);
assert_eq!(p.list_kinds(&kinds), wanted);
let _ = std::fs::remove_dir_all(&dir);
}
}
+15 -2
View File
@@ -58,8 +58,8 @@ fn overlay_texel(overlay: u32) -> vec4<f32> {
if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); }
return vec4(1.0);
}
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
overlay: u32, color: vec4<f32>, light: vec4<u32>, normal: vec4<f32>) -> Out {
var out: Out;
out.clip = globals.view_proj * vec4(position, 1.0);
out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw);
@@ -90,6 +90,19 @@ fn overlay_texel(overlay: u32) -> vec4<f32> {
if overlay == 4u { out.spherical = length(position); }
return out;
}
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
return entity_vertex(position, uv, overlay, color, light, normal);
}
struct CloudInfo {
offset: vec4<f32>,
colors: array<vec4<f32>, 4>,
}
@group(1) @binding(0) var<uniform> cloud: CloudInfo;
@vertex fn vs_cloud(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
return entity_vertex(position + cloud.offset.xyz, uv, overlay, cloud.colors[light.x], light, normal);
}
// rendertype_end_portal.fsh: the layer colours.
const PORTAL_COLORS = array<vec3<f32>, 16>(
vec3(0.022087, 0.098399, 0.110818),
+6 -1
View File
@@ -435,8 +435,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
});
}
"minecraft:zombie" => {
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
for (key, value) in [
("IsBaby", Tag::Byte(0)),
("CanBreakDoors", Tag::Byte(0)),
("DrownedConversionTime", Tag::Int(-1)),
("InWaterTime", Tag::Int(-1)),
@@ -845,6 +845,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.health = health;
m.extra.flag2 = flag(tag, "wasOnGround");
}
// Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby
// zombies of trial spawners).
if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") {
crate::mobs::finalize::set_baby(&mut m, true);
}
crate::mobs::raider::read_nbt(&mut m, tag);
crate::mobs::riders::read_nbt(&mut m, tag);
// A mob saved mid-death finishes dying; one saved dead is dropped.
-16
View File
@@ -119,22 +119,6 @@ impl FogState {
}
}
/// The fog tables and evolving state kept by the game.
pub struct FogRenderer {
pub tables: FogTables,
pub state: FogState,
}
impl FogRenderer {
pub fn load(root: &Path, biomes: &Biomes) -> Self {
Self {
tables: FogTables::load(root, biomes),
state: FogState::default(),
}
}
pub fn setup(&self, input: &FogInputs) -> FogData {
setup_fog(&self.tables, &self.state, input)
}
}
/// `FluidState.getHeightForCamera`.
fn camera_fluid_height(world: &World, facts: &BlockFacts, b: [i32; 3]) -> Option<(Fluid, f64)> {
let s = facts.get(world.block(b[0], b[1], b[2]));
File diff suppressed because it is too large Load Diff
+6 -50
View File
@@ -7,6 +7,7 @@ use horizon_client::{
hud::HudBatch,
items::ItemStack,
text::{self, Style, Text},
toasts::Slide,
};
use serde_json::Value;
use std::{
@@ -68,51 +69,6 @@ impl Toast {
(fully_for as f64 / (5000.0 * multiplier / n).max(1.0) % n) as usize
}
}
/// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms,
/// eased by the square, and counts how long it has been fully shown.
#[derive(Default)]
struct Slide {
/// When it first updated; the times below are milliseconds since.
origin: Option<Instant>,
begun: bool,
/// `animationStartTime`.
start: i64,
/// `becameFullyVisibleAt`.
fully_at: i64,
show: bool,
/// `visiblePortion`: 0 off screen, 1 fully in.
portion: f32,
/// `fullyVisibleFor`.
fully_for: i64,
}
impl Slide {
const MS: i64 = 600;
/// `ToastInstance.update` at `now`; `wants_show` is the toast's own
/// update. The visibility it switched to (the sound to play), and whether
/// it has finished sliding out.
fn update(&mut self, now: i64, wants_show: impl FnOnce(i64) -> bool) -> (Option<bool>, bool) {
let was = self.show;
if !self.begun {
self.begun = true;
self.start = now;
self.show = true;
}
if self.show && now - self.start <= Self::MS {
self.fully_at = now;
}
self.fully_for = now - self.fully_at;
let progress = ((now - self.start) as f32 / Self::MS as f32).clamp(0.0, 1.0);
let progress = progress * progress;
self.portion = if self.show { progress } else { 1.0 - progress };
let wanted = wants_show(self.fully_for);
if wanted != self.show {
self.start = now - ((1.0 - self.portion) * Self::MS as f32) as i64;
self.show = wanted;
}
let finished = !self.show && now - self.start > Self::MS;
((self.show != was).then_some(self.show), finished)
}
}
#[derive(Default)]
pub(super) struct AdvState {
pub(super) tree: Arc<Tree>,
@@ -153,7 +109,7 @@ impl adv::World for View<'_, '_> {
let name = self.0.res.facts.get(state).name.to_string();
let props = self
.0
.res
.pack
.assets
.registry
.state(state)
@@ -670,7 +626,7 @@ impl Game<'_> {
}
/// `EnterBlockTrigger`: the block, its state properties and the player.
pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) {
let Some(definition) = self.res.assets.registry.state(state).cloned() else {
let Some(definition) = self.pack.assets.registry.state(state).cloned() else {
return;
};
let me = self.player_entity();
@@ -803,11 +759,11 @@ impl Game<'_> {
if let Some((station, item)) = recipe {
// RecipeToast: black description under a purple title, the
// station at 0.6 scale in the corner over the cycling result.
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
let start = batch.vertices.len();
@@ -816,7 +772,7 @@ impl Game<'_> {
self.draw_item_model(batch, &item, x + 8.0, 8.0);
return;
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
let (key, color) = match frame {
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
@@ -257,7 +257,7 @@ impl Game<'_> {
}
/// `AdvancementWidget`'s title lines, description lines and width.
fn adv_widget_text(&self, i: usize) -> (Vec<Text>, Vec<Text>, f32) {
let font = &self.res.atlas.font;
let font = &self.atlas.font;
let a = &self.adv.tree.list[i];
let Some(d) = &a.display else {
return (Vec::new(), Vec::new(), 0.0);
@@ -320,7 +320,7 @@ impl Game<'_> {
let (sx, sy) = self.adv_ui.scroll.unwrap_or_default();
let (sx, sy) = (sx.floor() as i32, sy.floor() as i32);
self.adv_tick_hover(&view, sx, sy, left, top);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("gui.advancements", &[]);
let tw = atlas.font.width_text(&title);
@@ -432,7 +432,7 @@ impl Game<'_> {
}
let (x, y) = pos(i);
let (x, y) = ((ox + x) as f32, (oy + y) as f32);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_scaled(
atlas,
frame_sprite(d.frame, done),
@@ -449,7 +449,7 @@ impl Game<'_> {
}
}
// The window, tabs and title.
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_region(
atlas,
"gui/advancements/window",
@@ -463,7 +463,7 @@ impl Game<'_> {
let (x, y) = tab_pos(ty, i);
let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab);
batch.sprite_scaled(
&self.res.atlas,
&self.atlas,
&sprite,
left + x,
top + y,
@@ -482,7 +482,7 @@ impl Game<'_> {
}
}
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else(
|| Text::translate("gui.advancements", &[]),
|d| text_of(&d.title),
@@ -497,7 +497,7 @@ impl Game<'_> {
}
}
// Done.
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0);
let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0);
ui::button(
@@ -520,7 +520,7 @@ impl Game<'_> {
let (cx, cy) = self.cursor;
if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 {
if let Some(d) = &tree.list[t].display {
ui::tooltip(batch, &self.res.atlas, &[text_of(&d.title)], self.cursor);
ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor);
}
break;
}
@@ -604,7 +604,7 @@ impl Game<'_> {
],
)
});
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32;
let top_side = title_bottom + desc_h >= INSIDE_H;
let amount = if a.criteria.is_empty() || total == 0 {
+24 -4
View File
@@ -51,7 +51,7 @@ pub(super) const HELP: &[&str] = &[
"scroll-at X Y STEPS turn the wheel at GUI pixel X Y (positive scrolls up)",
"command TEXT run a /command",
"pause open the pause menu",
"wait TICKS wait for game ticks to pass",
"wait TICKS wait for game ticks to pass (held keys stay held)",
"stop cancel the running action and release every key",
];
@@ -231,6 +231,13 @@ enum TaskKind {
report_tick: u64,
},
}
impl TaskKind {
/// Whether the keys and buttons are released when the task ends. A wait
/// holds nothing, so what `key w down` pressed stays down through it.
fn releases_input(&self) -> bool {
!matches!(self, TaskKind::Wait { .. })
}
}
struct Goto {
target: [f64; 3],
near: f64,
@@ -294,7 +301,7 @@ pub(super) enum Handled {
impl Game<'_> {
pub(super) fn state_string(&self, state: BlockStateId) -> String {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return "?".into();
};
if s.properties.is_empty() {
@@ -389,6 +396,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
Screen::CommandBlock => "command-block",
}
}
pub(super) fn inventory_counts(&self) -> BTreeMap<String, i64> {
@@ -630,7 +638,7 @@ impl Game<'_> {
fn messages_value(&self, n: usize) -> Value {
let titles = &self.titles;
json!({
"chat": self.ui.chat.recent_lines(n),
"chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)),
"order": "newest first",
"title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(),
"subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(),
@@ -1654,7 +1662,9 @@ impl Game<'_> {
let result = self.step_task(&mut task.kind, timed_out);
match result {
Some(value) => {
self.release_agent_keys();
if task.kind.releases_input() {
self.release_agent_keys();
}
let _ = task.reply.send(value.to_string());
}
None => self.agent.task = Some(task),
@@ -1958,6 +1968,16 @@ impl Game<'_> {
mod tests {
use super::*;
#[test]
fn only_wait_keeps_held_input() {
assert!(!TaskKind::Wait { until_tick: 40 }.releases_input());
let jump = TaskKind::Jump {
release_tick: 4,
from_y: 64.0,
};
assert!(jump.releases_input());
}
#[test]
fn parses_flags_and_values() {
let a = parse_args(&["1", "2", "--near", "3", "--sprint", "--timeout=9", "-4"]);
@@ -124,7 +124,7 @@ impl Game<'_> {
continue;
};
let (Some(r), Some(part)) = (
self.res.atlas.sprites.get(texture.as_str()),
self.atlas.sprites.get(texture.as_str()),
assets.player.get(layer),
) else {
continue;
@@ -379,7 +379,7 @@ impl Game<'_> {
let mut dead = Vec::new();
for (i, a) in self.armor_stands.iter_mut().enumerate() {
a.tick(&mut scene);
if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) {
if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) {
dead.push(i);
}
}
@@ -403,7 +403,7 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let assets = &self.armor_stand_assets;
let sprites = &self.res.atlas.sprites;
let sprites = &self.atlas.sprites;
let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let Some(wood) = uv_of("entity/armorstand/armorstand") else {
return;
@@ -668,12 +668,12 @@ impl Game<'_> {
self.dim == super::Dim::Nether,
)),
};
self.res.item_renderer.submit_special(
self.pack.item_renderer.submit_special(
&special,
&serde_json::Value::Null,
false,
pose,
&self.res.atlas.sprites,
&self.atlas.sprites,
&self.item_host(),
&mut sink,
);
+4 -4
View File
@@ -150,11 +150,11 @@ impl Game<'_> {
.join("backdrop");
std::fs::create_dir_all(&root)?;
let save = Arc::new(SaveDir::new(root.join(format!("{seed}"))));
let res = &*self.res;
let (res, pack) = (&*self.res, &self.pack);
let inner = Arc::new(
VanillaTerrain::new(
&self.options.resources.join("worldgen"),
res.assets.registry,
pack.assets.registry,
&res.biomes,
seed,
)
@@ -164,10 +164,10 @@ impl Game<'_> {
Arc::new(Persistent {
inner: inner.clone(),
save: save.clone(),
registry: res.assets.clone(),
registry: pack.assets.clone(),
biomes: res.biomes.clone(),
}),
res.context.clone(),
pack.context.clone(),
res.threads.min(6),
);
streaming.radius = self.settings.render_distance.clamp(4, 10);
-14
View File
@@ -5,7 +5,6 @@ use super::Game;
use horizon_client::{
banner::{self, BannerLayer},
containers::BlockEntity,
items::ItemStack,
};
impl Game<'_> {
@@ -17,19 +16,6 @@ impl Game<'_> {
};
layer_textures(&self.res.stations.banners, &b.layers)
}
/// 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);
if !stack.item.ends_with("_banner") {
return;
}
if let Some(BlockEntity::Banner(b)) =
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
{
b.layers = banner::layers(stack).to_vec();
b.name = stack.custom_name().map(str::to_owned);
}
}
}
/// Texture names and tints of banner layers (`Sheets.getBannerSprite`).
+5 -11
View File
@@ -385,7 +385,7 @@ impl Game<'_> {
let levels = self.beacon_levels();
let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon);
let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some());
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.fill(
atlas,
0.0,
@@ -406,7 +406,7 @@ impl Game<'_> {
("block.minecraft.beacon.secondary", "Secondary Power", 169.0),
] {
let text = self.translate(key, fallback);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let w = HudBatch::text_width(atlas, &text);
batch.text(
atlas,
@@ -421,7 +421,7 @@ impl Game<'_> {
let x = [20.0, 41.0, 63.0, 86.0, 108.0][i];
self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0);
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let mut tooltip = None;
let button =
|batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| {
@@ -503,7 +503,7 @@ impl Game<'_> {
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
batch.fill(
&self.res.atlas,
&self.atlas,
ox + sx,
oy + sy,
16.0,
@@ -524,13 +524,7 @@ impl Game<'_> {
}
/// `BeaconRenderer`: each section's rotating solid beam and its glow.
pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let Some(s) = self
.res
.atlas
.sprites
.get("entity/beacon/beacon_beam")
.copied()
else {
let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else {
return;
};
let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32;
+2 -2
View File
@@ -63,7 +63,7 @@ impl HiveHost for GameHive<'_, '_> {
impl Game<'_> {
fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let mut s = registry.state(state)?.clone();
s.properties
.insert("honey_level".to_owned(), level.to_string());
@@ -82,7 +82,7 @@ impl Game<'_> {
{
return None;
}
let props = &self.res.assets.registry.state(state)?.properties;
let props = &self.pack.assets.registry.state(state)?.properties;
let honey = props.get("honey_level").and_then(|v| v.parse().ok());
let facing = beehive::facing_step(props.get("facing").map(String::as_str));
Some((honey, facing))
@@ -12,6 +12,7 @@ use horizon_client::{
save::number,
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::nbt::Tag;
use std::collections::HashMap;
/// The handle of the local player among a bell's gathered entities.
@@ -279,7 +280,7 @@ impl Game<'_> {
Ticker::Conduit => {
let world = &self.world;
let facts = &self.res.facts;
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let is_water = |p: [i32; 3]| {
facts.get(world.block(p[0], p[1], p[2])).fluid
== horizon_client::blocks::Fluid::Water
@@ -340,8 +341,15 @@ impl Game<'_> {
/// The End gateway at `pos` as its chunk was loaded: `Age` from the saved
/// block entity (`getUpdateTag`), or a new gateway.
fn gateway_loaded(&self, pos: [i32; 3]) -> EndGateway {
let age = self
.world
let age = self.saved_tag(pos).and_then(|t| number(t.get("Age")));
EndGateway {
age: age.unwrap_or(0),
teleport_cooldown: 0,
}
}
/// The block entity at `pos` Horizon keeps as loaded, if any.
fn saved_tag(&self, pos: [i32; 3]) -> Option<&Tag> {
self.world
.chunks
.get(&(pos[0] >> 4, pos[2] >> 4))
.and_then(|c| c.saved.as_deref())
@@ -352,16 +360,26 @@ impl Game<'_> {
.eq(&pos.map(|v| Some(i64::from(v))))
})
})
.and_then(|t| number(t.get("Age")));
EndGateway {
age: age.unwrap_or(0),
teleport_cooldown: 0,
}
}
/// The renderer's view of the block entity at `pos`.
/// The renderer's view of the block entity at `pos`, with a decorated
/// pot's saved `sherds` (back, left, right, front).
pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim {
let state = self.world.block(pos[0], pos[1], pos[2]);
let sherds = if &*self.res.facts.get(state).name == "minecraft:decorated_pot" {
let sherds = self.saved_tag(pos).and_then(|t| t.get("sherds"));
["back", "left", "right", "front"].map(|side| match sherds.and_then(|s| s.get(side)) {
// An item id, or the item stack the processed templates hold.
Some(Tag::String(id)) => Some(id.to_string_lossy()),
Some(stack) => {
horizon_client::save::item_from_nbt(stack).map(|s| s.item.to_string())
}
None => None,
})
} else {
Default::default()
};
self.be_anims
.block_anim(pos, self.world.game_time, partial, Default::default())
.block_anim(pos, self.world.game_time, partial, sherds)
}
/// `ChestLidController.getOpenness(partial)` at `pos`.
pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 {
@@ -0,0 +1,117 @@
//! Block entities and the items that carry them
//! (`horizon_client::block_entity_item`): the item Pick Block gives, with the
//! block entity's data on Ctrl in creative, and the data and components a
//! placed item gives its block entity.
use super::Game;
use horizon_client::{
block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, items::ItemStack, save,
};
use horizon_world::nbt::{Compound, Tag};
/// The component patch of `stack`.
fn components(stack: &ItemStack) -> Compound {
match item_data::encode_components(stack) {
Some(Tag::Compound(c)) => c,
_ => Compound::new(),
}
}
impl Game<'_> {
/// The block entity at `key` as vanilla saves it, with its custom name.
fn saved_block_entity(&self, key: (i32, i32, i32)) -> Option<Tag> {
let entity = self.world.block_entities.get(&key)?;
let block = &self
.res
.facts
.get(self.world.block(key.0, key.1, key.2))
.name;
let mut tag = save::encode_block_entity(key, entity, block);
if let (Some(name), Tag::Compound(map)) = (self.world.block_names.get(&key), &mut tag) {
map.insert("CustomName".into(), Tag::String(name.as_str().into()));
}
block_entity_nbt::canonical(&tag)
}
/// `BlockState.getCloneItemStack` of the block at `pos`, then, with
/// `include_data`, `ServerGamePacketListenerImpl.addBlockDataToItem`.
pub(super) fn picked_stack(&self, pos: [i32; 3], include_data: bool) -> Option<ItemStack> {
let key = (pos[0], pos[1], pos[2]);
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state);
if &*facts.item == "minecraft:air" {
return None;
}
let mut stack = ItemStack::new(&facts.item, 1);
let mut patch = Compound::new();
// BeehiveBlock.getCloneItemStack: the honey level as the item's block state.
if include_data
&& let Some(level) = self
.pack
.assets
.registry
.state(state)
.filter(|s| matches!(s.name.as_str(), "minecraft:beehive" | "minecraft:bee_nest"))
.and_then(|s| s.properties.get("honey_level"))
{
patch.insert(
"minecraft:block_state".into(),
Tag::compound([("honey_level", Tag::String(level.as_str().into()))]),
);
}
// AbstractBannerBlock.getCloneItemStack: the banner's own item
// (BannerBlockEntity.getItem), data or not.
let banner = matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Banner(_))
);
if (include_data || banner)
&& let Some(saved) = self.saved_block_entity(key)
{
patch.extend(block_entity_item::pick(&saved));
}
if !patch.is_empty() {
let mut all = components(&stack);
all.extend(patch);
(stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(all)));
}
Some(stack)
}
/// `BlockItem.updateCustomBlockEntityTag` and `updateBlockEntityComponents`
/// for the block entity just placed at `pos` from `stack`; `game_master`:
/// the placer can use game master blocks (a dispenser can't).
pub(super) fn apply_placed_item(
&mut self,
pos: [i32; 3],
stack: &ItemStack,
game_master: bool,
) {
let key = (pos[0], pos[1], pos[2]);
self.pending.banner.remove(&pos);
let Some(saved) = self.saved_block_entity(key) else {
return;
};
let placed = block_entity_item::place(&saved, &components(stack), game_master);
if placed == saved {
return;
}
let Some((_, mut entity)) = save::decode_block_entity(&placed) else {
return;
};
// The new crafter's state flag (CrafterBlock.newBlockEntity), which
// its saved data has no part of.
if let (BlockEntity::Crafter(new), Some(BlockEntity::Crafter(old))) =
(&mut entity, self.world.block_entities.get(&key))
{
new.state_triggered = old.state_triggered;
}
// Banners and signs keep their name themselves.
if !matches!(entity, BlockEntity::Banner(_) | BlockEntity::Sign(_)) {
match save::text(placed.get("CustomName")) {
Some(name) => self.world.block_names.insert(key, name),
None => self.world.block_names.remove(&key),
};
}
self.world.block_entities.insert(key, entity);
}
}
+3 -3
View File
@@ -33,7 +33,7 @@ fn parse_state(text: &str) -> Result<BlockState> {
impl Game<'_> {
fn state_text(&self, state: BlockStateId) -> String {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return "?".into();
};
if s.properties.is_empty() {
@@ -69,7 +69,7 @@ impl Game<'_> {
"setblock" => {
let pos = [int(1)?, int(2)?, int(3)?];
let state = self
.res
.pack
.assets
.registry
.resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?;
@@ -81,7 +81,7 @@ impl Game<'_> {
"fill" => {
let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]);
let state = self
.res
.pack
.assets
.registry
.resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?;
-1
View File
@@ -712,7 +712,6 @@ impl Game<'_> {
};
let folder = if b.chest { "chest_boat" } else { "boat" };
let Some(uv) = self
.res
.atlas
.sprites
.get(&format!("entity/{folder}/{}", b.wood))
+4 -4
View File
@@ -45,7 +45,7 @@ pub(super) enum BookScreen {
}
impl Game<'_> {
fn book_lines(&self, page: &str) -> Vec<Text> {
self.res.atlas.font.split(&Text::literal(page), 114.0)
self.atlas.font.split(&Text::literal(page), 114.0)
}
/// `WritableBookItem.use` / `WrittenBookItem.use`.
pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool {
@@ -242,7 +242,7 @@ impl Game<'_> {
/// the page (`MultilineTextField.insertText`: line breaks kept, cut to
/// the 1024 characters left, rejected when it overflows the 14 lines).
fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
let font = &self.res.atlas.font;
let font = &self.atlas.font;
match self.book.as_mut() {
Some(BookScreen::Edit {
signing: true,
@@ -363,7 +363,7 @@ impl Game<'_> {
}
fn set_lectern_property(&mut self, key: (i32, i32, i32), name: &str, value: bool) {
let state = self.world.block(key.0, key.1, key.2);
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(mut s) = registry.state(state).cloned() else {
return;
};
@@ -549,7 +549,7 @@ impl Game<'_> {
}
pub(super) fn draw_book(&self, batch: &mut HudBatch) {
let Some(book) = &self.book else { return };
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
let (mx, my) = self.cursor;
let hover =
@@ -89,17 +89,17 @@ impl Game<'_> {
if is_locked {
locked = true;
if scaling || locking {
batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0);
batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0);
}
}
if scaling && scale >= 4 {
locked = true;
batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0);
batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0);
}
}
let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| {
batch.sprite(
&game.res.atlas,
&game.atlas,
&format!("gui/sprites/container/cartography_table/{name}"),
ox + x,
oy + y,
+21 -23
View File
@@ -3,7 +3,7 @@
use super::{Dim, Game, Screen};
use horizon_client::{
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
command::{Registries, vanilla},
command::Registries,
gamerules::GameRules,
hud::{HudBatch, rgba},
screen_draw::Measure,
@@ -226,7 +226,7 @@ impl Game<'_> {
.map(|k| horizon_client::command::args::normalize(k))
.collect();
reg.block_tags.sort();
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let mut blocks: BTreeMap<String, BTreeMap<String, Vec<String>>> = BTreeMap::new();
for id in 0..registry.len() {
let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32))
@@ -389,9 +389,9 @@ impl Game<'_> {
.as_ref()
.map_or([1280, 720], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
};
let mut screen = ChatScreen::new(
@@ -428,7 +428,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
let heard = self.mods.mods.is_running().then(|| text.plain());
self.ui.chat.add(
&self.res.atlas,
&self.atlas,
text,
Some(SYSTEM_INDICATOR),
self.ticks,
@@ -441,9 +441,9 @@ impl Game<'_> {
/// Keys while the chat screen is open.
pub(super) fn chat_key(&mut self, event: &KeyEvent) {
if let Some(shortcut) = self.edit_shortcut(event) {
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
};
if let Some(screen) = self.ui.chat_screen.as_mut() {
@@ -487,9 +487,9 @@ impl Game<'_> {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
};
match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) {
@@ -513,9 +513,9 @@ impl Game<'_> {
}
/// Text typed into the chat box (control socket `chat`).
pub(super) fn chat_type(&mut self, text: &str) {
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
};
if let Some(screen) = self.ui.chat_screen.as_mut() {
@@ -536,7 +536,7 @@ impl Game<'_> {
let heard = self.mods.mods.is_running().then(|| line.plain());
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
.add(&self.atlas, line, None, self.ticks, focused);
if let Some(line) = heard {
self.mods_chat(&line);
}
@@ -564,9 +564,9 @@ impl Game<'_> {
let height = self.renderer.as_ref().map_or(720.0, |r| {
HudBatch::new([r.config.width, r.config.height]).height
});
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
};
if let Some(screen) = self.ui.chat_screen.as_mut() {
@@ -577,7 +577,7 @@ impl Game<'_> {
return;
}
match self.ui.chat.click_at(
&self.res.atlas.font,
&self.atlas.font,
height as i32,
cursor.0 as f64,
cursor.1 as f64,
@@ -603,17 +603,15 @@ impl Game<'_> {
if self.ui.hide_gui && !focused {
return;
}
self.ui
.chat
.draw(batch, &self.res.atlas, self.ticks, focused);
self.ui.chat.draw(batch, &self.atlas, self.ticks, focused);
}
pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
};
screen.resize(&m, &c, batch.width as i32, batch.height as i32);
@@ -629,7 +627,7 @@ impl Game<'_> {
.chat_opened
.map_or(0, |t| t.elapsed().as_millis() as u64);
let draws = screen.draw(&m, mouse, blink, background);
horizon_client::screen_draw::paint(batch, &self.res.atlas, &draws);
horizon_client::screen_draw::paint(batch, &self.atlas, &draws);
self.ui.chat_screen = Some(screen);
}
/// Advance the overworld clock (ServerClockManager.tick) when
@@ -821,11 +819,11 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, message, None, self.ticks, focused);
.add(&self.atlas, message, None, self.ticks, focused);
}
#[allow(dead_code)]
fn chat_debug_fill(&self, batch: &mut HudBatch) {
batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
}
}
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
+9 -5
View File
@@ -46,6 +46,9 @@ impl Game<'_> {
let Some(title) = self.title.as_mut() else {
return;
};
if title.has_caret_field() {
return title.field_shortcut(shortcut, &mut self.clipboard);
}
if let Some((id, value, max)) = title.focused_field() {
let changed = Self::append_shortcut(
&mut self.text_selection,
@@ -60,15 +63,16 @@ impl Game<'_> {
}
}
}
/// Typing or a backspace in an append-only field of the title screens:
/// Select All's selection is replaced first.
/// Typing or a backspace in a field of the title screens: in the server
/// screens' append-only fields Select All's selection is replaced first.
pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) {
let Some(title) = self.title.as_mut() else {
return;
};
let cleared = title
.focused_field()
.is_some_and(|(id, value, _)| self.text_selection.take(id, value));
let cleared = !title.has_caret_field()
&& title
.focused_field()
.is_some_and(|(id, value, _)| self.text_selection.take(id, value));
if cleared {
title.search_changed();
}
@@ -0,0 +1,638 @@
//! Command blocks: `CommandBlock`'s placement (`setPlacedBy`), its scheduled
//! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand`
//! through the command system with the block's output, and
//! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it.
use super::{Game, Screen, commands::execute::Source};
use horizon_client::{
command_block::{self, CommandBlock, Mode},
containers::BlockEntity,
hud::{HudBatch, rgba},
text::{self, Text},
ui::{self, EditBox},
world::World,
};
use horizon_core::position::BlockPos;
use horizon_world::{
chunk::BlockState,
level::flags,
registry::{BlockRegistry, BlockStateId},
};
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
};
type Pos = (i32, i32, i32);
/// The open `CommandBlockEditScreen`.
pub(super) struct CommandBlockScreen {
pos: Pos,
command: EditBox,
previous: EditBox,
track_output: bool,
mode: Mode,
conditional: bool,
auto: bool,
}
#[derive(Clone, Copy, PartialEq)]
enum Button {
Output,
Mode,
Conditional,
Auto,
Done,
Cancel,
}
/// `EditBox.textColorUneditable`.
const UNEDITABLE: u32 = 0xFF70_7070;
impl CommandBlockScreen {
/// `AbstractCommandBlockEditScreen.init` and `CommandBlockEditScreen`'s
/// buttons, in GUI pixels of a `w`×`h` screen.
fn buttons(w: f32, h: f32) -> [(Button, f32, f32, f32); 6] {
let mid = (w / 2.0).floor();
let low = (h / 4.0).floor() + 132.0;
[
(Button::Output, mid + 130.0, 135.0, 20.0),
(Button::Mode, mid - 154.0, 165.0, 100.0),
(Button::Conditional, mid - 50.0, 165.0, 100.0),
(Button::Auto, mid + 54.0, 165.0, 100.0),
(Button::Done, mid - 154.0, low, 150.0),
(Button::Cancel, mid + 4.0, low, 150.0),
]
}
fn label(&self, b: Button) -> Text {
let tr = |key: &str| Text::translate(key, &[]);
match b {
Button::Output => Text::literal(if self.track_output { "O" } else { "X" }),
Button::Mode => tr(self.mode.label()),
Button::Conditional => tr(if self.conditional {
"advMode.mode.conditional"
} else {
"advMode.mode.unconditional"
}),
Button::Auto => tr(if self.auto {
"advMode.mode.autoexec.bat"
} else {
"advMode.mode.redstoneTriggered"
}),
Button::Done => tr("gui.done"),
Button::Cancel => tr("gui.cancel"),
}
}
/// `updatePreviousOutput`.
fn show_previous(&mut self, block: &CommandBlock) {
let shown = if self.track_output {
block.last_output_string()
} else {
"-".to_owned()
};
self.previous.set_value(&shown);
}
}
fn state_of(registry: &BlockRegistry, state: BlockStateId) -> Option<&BlockState> {
registry.state(state)
}
fn facing_step(state: &BlockState) -> [i32; 3] {
match state.properties.get("facing").map(String::as_str) {
Some("down") => [0, -1, 0],
Some("up") => [0, 1, 0],
Some("south") => [0, 0, 1],
Some("west") => [-1, 0, 0],
Some("east") => [1, 0, 0],
_ => [0, 0, -1],
}
}
/// `Direction.toYRot`: south 0, west 90, north 180, east (and up/down) 270.
fn facing_yaw(state: &BlockState) -> f32 {
match state.properties.get("facing").map(String::as_str) {
Some("south") => 0.0,
Some("west") => 90.0,
Some("north") => 180.0,
_ => 270.0,
}
}
fn conditional(state: &BlockState) -> bool {
state
.properties
.get("conditional")
.is_some_and(|c| c == "true")
}
fn offset(pos: Pos, step: [i32; 3]) -> Pos {
(pos.0 + step[0], pos.1 + step[1], pos.2 + step[2])
}
fn command_block_mut(world: &mut World, pos: Pos) -> Option<&mut CommandBlock> {
match world.block_entities.get_mut(&pos)? {
BlockEntity::CommandBlock(c) => Some(c),
_ => None,
}
}
/// `CommandBlockEntity.markConditionMet`: a conditional block needs the
/// command block behind it to have succeeded.
pub(super) fn mark_condition_met(world: &mut World, registry: &BlockRegistry, pos: Pos) -> bool {
let Some(state) = state_of(registry, world.block(pos.0, pos.1, pos.2)) else {
return false;
};
let mut met = true;
if conditional(state) {
let back = facing_step(state).map(|v| -v);
let behind = offset(pos, back);
let behind_block = state_of(registry, world.block(behind.0, behind.1, behind.2))
.is_some_and(|s| Mode::of_block(&s.name).is_some());
met = behind_block
&& matches!(world.block_entities.get(&behind),
Some(BlockEntity::CommandBlock(c)) if c.success_count > 0);
}
if let Some(c) = command_block_mut(world, pos) {
c.condition_met = met;
}
met
}
/// `CommandBlockEntity.setPowered` from `CommandBlock.setPoweredAndUpdate`
/// (the level's neighbour hook): the previous flag and `isAutomatic`; a
/// rising signal that will tick the block checks its condition.
pub(super) fn set_powered(
world: &mut World,
registry: &BlockRegistry,
pos: Pos,
powered: bool,
) -> Option<(bool, bool)> {
let mode = state_of(registry, world.block(pos.0, pos.1, pos.2))
.and_then(|s| Mode::of_block(&s.name))?;
let c = command_block_mut(world, pos)?;
let (was, auto) = (c.powered, c.auto);
c.powered = powered;
if command_block::power_schedules(mode, was, powered, auto) {
mark_condition_met(world, registry, pos);
}
Some((was, auto))
}
/// `getAnalogOutputSignal`: the success count.
pub(super) fn analog_signal(world: &World, pos: Pos) -> Option<i32> {
match world.block_entities.get(&pos)? {
BlockEntity::CommandBlock(c) => Some(c.success_count),
_ => None,
}
}
impl Game<'_> {
/// `Player.canUseGameMasterBlocks`: creative with game master commands.
pub(super) fn can_use_game_master_blocks(&self) -> bool {
self.creative && self.ui.registries.permission >= 2
}
fn command_block(&self, pos: Pos) -> Option<&CommandBlock> {
match self.world.block_entities.get(&pos)? {
BlockEntity::CommandBlock(c) => Some(c),
_ => None,
}
}
fn block_state_at(&self, pos: Pos) -> Option<&'static BlockState> {
let registry = self.pack.assets.registry;
state_of(registry, self.world.block(pos.0, pos.1, pos.2))
}
fn schedule_command_block(&mut self, pos: Pos) {
let at = BlockPos::new(pos.0, pos.1, pos.2);
self.with_level(|b, level, ticks| b.schedule_tick(level, ticks, at, 1));
}
/// `CommandBlockEntity.scheduleTick`.
fn schedule_command_block_tick(&mut self, pos: Pos) {
mark_condition_met(&mut self.world, self.pack.assets.registry, pos);
self.schedule_command_block(pos);
}
fn update_output_signal(&mut self, pos: Pos) {
let at = BlockPos::new(pos.0, pos.1, pos.2);
self.with_level(|b, level, ticks| b.update_neighbour_for_output_signal(level, ticks, at));
}
/// `CommandBlock.setPlacedBy`: unless the item carried block entity data
/// (`defaults` false), output tracking follows `send_command_feedback` and
/// the block's own automatic flag; then the block takes the signal around it.
pub(super) fn command_block_placed(&mut self, pos: Pos, defaults: bool) {
let feedback = self.ui.rules.bool("send_command_feedback");
let Some(name) = self.block_state_at(pos).map(|s| s.name.as_str()) else {
return;
};
let auto = command_block::automatic_block(name);
if defaults && let Some(c) = command_block_mut(&mut self.world, pos) {
c.track_output = feedback;
c.auto = auto;
}
let at = BlockPos::new(pos.0, pos.1, pos.2);
let signal = self.with_level(|b, level, ticks| b.has_neighbor_signal(level, ticks, at));
let registry = self.pack.assets.registry;
if let Some((was, auto)) = set_powered(&mut self.world, registry, pos, signal)
&& signal
&& !was
&& !auto
&& !command_block::automatic_block(name)
{
self.schedule_command_block(pos);
}
}
/// `CommandBlock.tick`.
pub(super) fn command_block_tick(&mut self, pos: BlockPos) {
let key = (pos.x, pos.y, pos.z);
let Some(state) = self.block_state_at(key) else {
return;
};
let Some(mode) = Mode::of_block(&state.name) else {
return;
};
let Some(was_met) = self.command_block(key).map(|c| c.condition_met) else {
return;
};
if mode == Mode::Auto {
mark_condition_met(&mut self.world, self.pack.assets.registry, key);
}
match command_block::tick_action(mode, was_met, conditional(state)) {
Some(true) => self.command_block_execute(key, state),
Some(false) => {
if let Some(c) = command_block_mut(&mut self.world, key) {
c.success_count = 0;
}
}
None => {}
}
if let Some(c) = self.command_block(key)
&& command_block::repeats(mode, c.powered, c.auto)
{
self.schedule_command_block(key);
}
self.update_output_signal(key);
}
/// `CommandBlock.execute`: the command (or no successes without one),
/// then the chain in front.
fn command_block_execute(&mut self, pos: Pos, state: &BlockState) {
let has_command = self
.command_block(pos)
.is_some_and(|c| !c.command.is_empty());
if has_command {
self.perform_command_block(pos);
} else if let Some(c) = command_block_mut(&mut self.world, pos) {
c.success_count = 0;
}
self.execute_chain(pos, facing_step(state));
}
/// `CommandBlock.executeChain`: the chain command blocks in front, each
/// facing on to the next, up to `max_command_sequence_length`.
fn execute_chain(&mut self, start: Pos, mut step: [i32; 3]) {
let registry = self.pack.assets.registry;
let limit = self.ui.rules.int("max_command_sequence_length");
let mut remaining = limit;
let mut pos = start;
while remaining > 0 {
remaining -= 1;
pos = offset(pos, step);
let Some(state) = self.block_state_at(pos) else {
break;
};
if Mode::of_block(&state.name) != Some(Mode::Sequence) {
break;
}
let Some(c) = self.command_block(pos) else {
break;
};
if c.powered || c.auto {
if mark_condition_met(&mut self.world, registry, pos) {
if !self.perform_command_block(pos) {
break;
}
self.update_output_signal(pos);
} else if conditional(state)
&& let Some(c) = command_block_mut(&mut self.world, pos)
{
c.success_count = 0;
}
}
step = facing_step(state);
}
if remaining <= 0 {
log::warn!(
"Command Block chain tried to execute more than {} steps!",
limit.max(0)
);
}
}
/// `BaseCommandBlock.performCommand`: runs the command as the block, at
/// game master level, counting the successful results. False when it
/// already ran this game tick.
fn perform_command_block(&mut self, pos: Pos) -> bool {
let game_time = self.world.game_time;
let Some(c) = command_block_mut(&mut self.world, pos) else {
return false;
};
if c.last_execution == game_time {
return false;
}
if c.command.eq_ignore_ascii_case("Searge") {
c.last_output = Some(Text::literal("#itzlipofutzli"));
c.success_count = 1;
return true;
}
c.success_count = 0;
let command = c.command.clone();
if self.ui.rules.bool("command_blocks_work") && !command.is_empty() {
if let Some(c) = command_block_mut(&mut self.world, pos) {
c.last_output = None;
}
let Some(state) = self.block_state_at(pos) else {
return false;
};
let source = Source {
entity: None,
pos: [
f64::from(pos.0) + 0.5,
f64::from(pos.1) + 0.5,
f64::from(pos.2) + 0.5,
],
rot: [facing_yaw(state), 0.0],
eyes: false,
silent: false,
store: None,
elsewhere: false,
block: Some(pos),
};
// performPrefixedCommand: a leading slash is allowed.
let line = command.strip_prefix('/').unwrap_or(&command).to_owned();
let outer = self.cmds.results.replace(Vec::new());
let level = std::mem::replace(&mut self.ui.registries.permission, 2);
self.with_source(source, |g| g.run_command(&line));
self.ui.registries.permission = level;
let results = std::mem::replace(&mut self.cmds.results, outer).unwrap_or_default();
let successes = results.iter().filter(|(success, _)| *success).count();
if let Some(c) = command_block_mut(&mut self.world, pos) {
c.success_count = successes as i32;
}
}
if let Some(c) = command_block_mut(&mut self.world, pos) {
c.last_execution = if c.update_last_execution {
game_time
} else {
-1
};
}
true
}
/// `CloseableCommandBlockSource.sendSystemMessage`: the block's last
/// output, stamped with the time. Nothing when it doesn't track output
/// (`CommandSource.NULL`).
pub(super) fn command_block_output(&mut self, pos: Pos, message: Text) {
if let Some(c) = command_block_mut(&mut self.world, pos)
&& c.track_output
{
let time = chrono::Local::now().format("[%H:%M:%S] ").to_string();
c.last_output = Some(Text::literal(time).append(message));
}
}
/// `CommandSourceStack.sendSuccess` from a command block: its output when
/// `send_command_feedback`, and `broadcastToAdmins` when
/// `command_block_output`.
pub(super) fn command_block_success(&mut self, pos: Pos, message: Text) {
let Some(name) = self
.command_block(pos)
.filter(|c| c.track_output)
.map(CommandBlock::name)
else {
return;
};
let feedback = self.ui.rules.bool("send_command_feedback");
if feedback {
self.command_block_output(pos, message.clone());
}
if feedback && self.ui.rules.bool("command_block_output") {
let broadcast = Text::translate("chat.type.admin", &[name, message])
.with_color(text::GRAY)
.italic();
self.system_message(broadcast);
}
}
/// `LocalPlayer.openCommandBlock`.
pub(super) fn open_command_block(&mut self, pos: Pos) {
let Some(block) = self.command_block(pos).cloned() else {
return;
};
let Some(state) = self.block_state_at(pos) else {
return;
};
let mut command = EditBox::new(0.0, 50.0, 300.0, 20.0);
command.max_length = 32500;
command.set_value(&block.command);
command.focused = true;
let mut previous = EditBox::new(0.0, 135.0, 276.0, 20.0);
previous.max_length = 32500;
previous.text_color = UNEDITABLE;
previous.focused = false;
let mut screen = CommandBlockScreen {
pos,
command,
previous,
track_output: block.track_output,
mode: Mode::of_block(&state.name).unwrap_or(Mode::Redstone),
conditional: conditional(state),
auto: block.auto,
};
screen.show_previous(&block);
self.command_block_screen = Some(screen);
self.screen = Screen::CommandBlock;
self.capture(false);
}
pub(super) fn close_command_block(&mut self) {
self.command_block_screen = None;
self.screen = Screen::Playing;
self.capture(true);
}
pub(super) fn draw_command_block(&mut self, batch: &mut HudBatch) {
let Some(mut s) = self.command_block_screen.take() else {
return;
};
// AbstractCommandBlockEditScreen.tick: the block is gone.
if self.command_block(s.pos).is_none() {
self.close_command_block();
return;
}
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
let mid = (w / 2.0).floor();
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("advMode.setCommand", &[]);
let tw = atlas.font.width_text(&title);
batch.text_styled(
atlas,
&title,
(mid - tw / 2.0).floor(),
20.0,
u32::MAX,
true,
);
let grey = rgba(160, 160, 160, 255);
let label = Text::translate("advMode.command", &[]);
batch.text_styled(atlas, &label, mid - 149.0, 40.0, grey, true);
s.command.x = mid - 150.0;
s.command.draw(batch, atlas, None);
if !s.previous.value.is_empty() {
let label = Text::translate("advMode.previousOutput", &[]);
batch.text_styled(atlas, &label, mid - 149.0, 125.0, grey, true);
s.previous.x = mid - 150.0;
s.previous.draw(batch, atlas, None);
}
for (b, x, y, bw) in CommandBlockScreen::buttons(w, h) {
let hover = ui::hovered(self.cursor, x, y, bw, 20.0);
ui::button(batch, atlas, x, y, bw, 20.0, &s.label(b), true, hover);
}
self.command_block_screen = Some(s);
}
pub(super) fn command_block_click(&mut self) {
let Some(mut s) = self.command_block_screen.take() else {
return;
};
let size = self
.renderer
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let hit = CommandBlockScreen::buttons(b.width, b.height)
.into_iter()
.find(|(_, x, y, bw)| ui::hovered(self.cursor, *x, *y, *bw, 20.0))
.map(|b| b.0);
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
Some(Button::Output) => {
s.track_output = !s.track_output;
if let Some(block) = self.command_block(s.pos) {
s.show_previous(block);
}
}
Some(Button::Mode) => s.mode = s.mode.next(),
Some(Button::Conditional) => s.conditional = !s.conditional,
Some(Button::Auto) => s.auto = !s.auto,
Some(Button::Done) => {
self.set_command_block(&s);
self.close_command_block();
return;
}
Some(Button::Cancel) => {
self.close_command_block();
return;
}
None => {}
}
self.command_block_screen = Some(s);
}
/// `AbstractCommandBlockEditScreen.keyPressed`: Enter is Done, Escape
/// cancels, the rest edits the command.
pub(super) fn command_block_key(&mut self, event: &KeyEvent) {
if event.state != ElementState::Pressed {
return;
}
let PhysicalKey::Code(key) = event.physical_key else {
return;
};
match key {
KeyCode::Escape => return self.close_command_block(),
KeyCode::Enter | KeyCode::NumpadEnter => {
if let Some(s) = self.command_block_screen.take() {
self.set_command_block(&s);
}
return self.close_command_block();
}
_ => {}
}
let ctrl = self.keys.contains(&KeyCode::ControlLeft);
let shift = self.keys.contains(&KeyCode::ShiftLeft);
let shortcut = self.edit_shortcut(event);
let Some(s) = self.command_block_screen.as_mut() else {
return;
};
if let Some(shortcut) = shortcut {
s.command.shortcut(shortcut, &mut self.clipboard);
} else if !s.command.key(key, ctrl, shift) && !ctrl {
self.command_block_type(event.text.as_deref().unwrap_or(""));
}
}
/// Characters typed into the command box (`StringUtil.isAllowedChatCharacter`).
pub(super) fn command_block_type(&mut self, typed: &str) {
let allowed: String = typed
.chars()
.filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}')
.collect();
if let Some(s) = self.command_block_screen.as_mut()
&& !allowed.is_empty()
{
s.command.insert_text(&allowed);
}
}
/// `ServerGamePacketListenerImpl.handleSetCommandBlock`.
fn set_command_block(&mut self, s: &CommandBlockScreen) {
if !self.can_use_game_master_blocks() {
self.system_message(Text::translate("advMode.notAllowed", &[]));
return;
}
let pos = s.pos;
let registry = self.pack.assets.registry;
let Some(current) = self.block_state_at(pos) else {
return;
};
let Some(old_mode) = Mode::of_block(&current.name) else {
return;
};
if self.command_block(pos).is_none() {
return;
}
// The mode is the block, the conditional flag its state; the block
// entity stays.
let mut wanted = current.clone();
wanted.name = s.mode.block().to_owned();
wanted
.properties
.insert("conditional".into(), s.conditional.to_string());
if let Ok(id) = registry.resolve(&wanted)
&& wanted != *current
{
let entity = self.world.block_entities.remove(&pos);
let at = BlockPos::new(pos.0, pos.1, pos.2);
self.with_level(|b, level, ticks| {
b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS)
});
if let Some(entity) = entity {
self.world.block_entities.insert(pos, entity);
}
let _ = self.process_level_events();
}
let command = s.command.value.clone();
let Some(c) = command_block_mut(&mut self.world, pos) else {
return;
};
c.set_command(&command);
c.track_output = s.track_output;
if !s.track_output {
c.last_output = None;
}
// CommandBlockEntity.setAutomatic, then onModeSwitch.
let (was_auto, powered) = (c.auto, c.powered);
c.auto = s.auto;
if !was_auto && s.auto && !powered && s.mode != Mode::Sequence {
self.schedule_command_block_tick(pos);
}
if old_mode != s.mode && s.mode == Mode::Auto && (powered || s.auto) {
self.schedule_command_block_tick(pos);
}
if !command.is_empty() {
let key = if self.ui.rules.bool("command_blocks_work") {
"advMode.setCommand.success"
} else {
"advMode.setCommand.disabled"
};
self.system_message(Text::translate(key, &[Text::literal(command)]));
}
}
}
+27 -14
View File
@@ -143,13 +143,22 @@ impl Game<'_> {
if self.command_source.is_some_and(|s| s.silent) {
return;
}
self.system_message(Text::empty().append(message).with_color(text::RED));
let message = Text::empty().append(message).with_color(text::RED);
if let Some(block) = self.command_source.and_then(|s| s.block) {
self.command_block_output(block, message);
return;
}
self.system_message(message);
}
/// sendSuccess honouring `send_command_feedback`.
pub(super) fn feedback(&mut self, message: Text) {
if self.command_source.is_some_and(|s| s.silent) {
return;
}
if let Some(block) = self.command_source.and_then(|s| s.block) {
self.command_block_success(block, message);
return;
}
if self.ui.rules.bool("send_command_feedback") {
self.system_message(message);
}
@@ -315,11 +324,15 @@ impl Game<'_> {
/// Entity.getDisplayName.
pub(super) fn target_name(&self, t: Target) -> Text {
match t {
Target::Player => match self.score.board.players_team(PLAYER_NAME) {
// PlayerTeam.formatNameForTeam.
Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)),
None => Text::literal(PLAYER_NAME),
},
Target::Player => {
// A guest's commands name the guest.
let name = self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME);
match self.score.board.players_team(name) {
// PlayerTeam.formatNameForTeam.
Some(team) => team.formatted_name(Text::literal(name)),
None => Text::literal(name),
}
}
Target::Item(id) => {
let item = self
.dropped
@@ -327,7 +340,7 @@ impl Game<'_> {
.find(|i| i.id == id)
.map(|i| i.stack.item.to_string())
.unwrap_or_default();
Text::literal(self.res.names.item(&item))
Text::literal(self.pack.names.item(&item))
}
Target::Mob(id)
if self
@@ -770,7 +783,7 @@ impl Game<'_> {
_ => text::WHITE,
};
Text::literal("[")
.append(Text::literal(self.res.names.item(item)))
.append(Text::literal(self.pack.names.item(item)))
.append("]")
.with_color(color)
}
@@ -803,7 +816,7 @@ impl Game<'_> {
&[],
)
} else {
Text::literal(self.res.names.item(item))
Text::literal(self.pack.names.item(item))
};
let wrapped = Text::translate("chat.square_brackets", &[hover]);
if empty {
@@ -1443,7 +1456,7 @@ impl Game<'_> {
name: b.id.clone(),
properties: b.properties.iter().cloned().collect(),
};
self.res
self.pack
.assets
.registry
.resolve(&state)
@@ -1451,7 +1464,7 @@ impl Game<'_> {
}
/// BlockPredicateArgument test.
fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return false;
};
let name_ok = if b.tag {
@@ -1726,7 +1739,7 @@ impl Game<'_> {
let strict = ctx.has("strict");
// CloneCommands.clone sets every destination to a barrier first, so
// each copied state but a barrier counts as placed.
let barrier = self.res.assets.registry.default_state("minecraft:barrier");
let barrier = self.pack.assets.registry.default_state("minecraft:barrier");
let mut count = 0;
for (_, to, s, entity) in copies {
self.place_state(to, s, strict)?;
@@ -2253,7 +2266,7 @@ impl Game<'_> {
}
/// `PoiTypes`: the point of interest type of a block state.
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
let s = self.res.assets.registry.state(state)?;
let s = self.pack.assets.registry.state(state)?;
let name = s.name.strip_prefix("minecraft:")?;
Some(match name {
"blast_furnace" => "minecraft:armorer",
@@ -2529,7 +2542,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
.add(&self.atlas, line, None, self.ticks, focused);
Ok(1)
}
/// MessageArgument: `@p`-style selectors in a message become names.
@@ -494,7 +494,7 @@ impl Game<'_> {
return false;
};
let state = self.world.block(p[0], p[1], p[2]);
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return false;
};
let name = s.name.to_string();
@@ -180,7 +180,7 @@ impl Game<'_> {
}
pub(in crate::game) fn data_block_name(&self, p: [i32; 3]) -> String {
let state = self.world.block(p[0], p[1], p[2]);
self.res
self.pack
.assets
.registry
.state(state)
@@ -227,7 +227,7 @@ impl Game<'_> {
return Err(err(
"commands.enchant.failed.incompatible",
&[&stack.custom_name().map_or_else(
|| self.res.names.item(&stack.item).to_string(),
|| self.pack.names.item(&stack.item).to_string(),
str::to_owned,
)],
));
@@ -247,7 +247,7 @@ impl Game<'_> {
),
Some(item) => err(
"commands.enchant.failed.incompatible",
&[&self.res.names.item(&item)],
&[&self.pack.names.item(&item)],
),
});
}
@@ -26,6 +26,9 @@ pub(in crate::game) struct Source {
/// `execute in` another dimension than the one Horizon has loaded: none
/// of its chunks are loaded.
pub elsewhere: bool,
/// The command block whose output this source is
/// (`BaseCommandBlock.CloseableCommandBlockSource`).
pub block: Option<(i32, i32, i32)>,
}
/// Where `execute store` writes.
@@ -74,6 +77,7 @@ impl Game<'_> {
silent: false,
store: None,
elsewhere: false,
block: None,
}
}
/// The server as a source (function ticks and schedules): the world spawn.
@@ -86,6 +90,7 @@ impl Game<'_> {
silent: true,
store: None,
elsewhere: false,
block: None,
}
}
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
@@ -647,7 +652,7 @@ impl Game<'_> {
let facts = self.res.facts.get(state);
let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None;
let leaves = self
.res
.pack
.assets
.registry
.state(state)
@@ -25,7 +25,7 @@ impl Game<'_> {
.join("worldgen/blocks/structure-blocks.json"),
)
.ok()?;
StateTransforms::from_json(&json, self.res.assets.registry.len()).ok()
StateTransforms::from_json(&json, self.pack.assets.registry.len()).ok()
})
.as_ref()
}
@@ -64,7 +64,7 @@ impl Game<'_> {
};
return Some(Arc::new(StructureTemplate::from_nbt(
&named.tag,
self.res.assets.registry,
self.pack.assets.registry,
transforms,
)));
}
@@ -551,14 +551,14 @@ impl Game<'_> {
Some(seq) => {
let random = self.rand_sequences.get(&seq, self.level.seed);
self.res.items.block_drops(
self.res.assets.registry,
self.pack.assets.registry,
state,
tool.as_ref(),
random,
)
}
None => self.res.items.block_drops(
self.res.assets.registry,
self.pack.assets.registry,
state,
tool.as_ref(),
&mut self.world.random,
+1 -1
View File
@@ -13,7 +13,7 @@ impl Game<'_> {
/// The composter's `level` at `pos`, None when it isn't a composter.
pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option<i32> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let s = self.res.assets.registry.state(state)?;
let s = self.pack.assets.registry.state(state)?;
if &*s.name != "minecraft:composter" {
return None;
}
+30 -7
View File
@@ -11,7 +11,7 @@ use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode};
const HELP: &[&str] = &[
"status game, player, streaming and renderer state",
"key KEY down|up|tap press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
"key KEY down|up|tap|repeat press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
"release release every key and mouse button",
"mouse left|right|middle down|up|click",
"look YAW PITCH set the view direction in degrees",
@@ -201,7 +201,7 @@ impl Game<'_> {
}
// The zoom extra sees the key as the keyboard hook does.
let action = arg(2)?;
self.extras_key(physical, action != "up", false);
self.extras_key(physical, action != "up", action == "repeat");
if action == "tap" {
self.extras_key(physical, false, false);
}
@@ -233,6 +233,11 @@ impl Game<'_> {
self.keys.remove(&key);
self.physical_keys.remove(&key);
}
// The system's auto-repeat while the key is held.
"repeat" => {
self.physical_keys.insert(physical);
self.mapped_key(key, true, true)?;
}
"tap" => {
self.control_key_down(key)?;
self.keys.remove(&key);
@@ -240,9 +245,10 @@ impl Game<'_> {
self.debug_key(physical, horizon_client::debug_keys::KeyAction::Release);
}
other => {
return Err(
format!("key action must be down, up or tap, not {other}").into()
);
return Err(format!(
"key action must be down, up, tap or repeat, not {other}"
)
.into());
}
}
ok()
@@ -420,7 +426,11 @@ impl Game<'_> {
}
match self.screen {
Screen::Chat => self.chat_type(text),
Screen::Options => self.ui.options.type_text(&self.res.atlas, text),
Screen::CommandBlock => self.command_block_type(text),
Screen::Options => self.ui.options.type_text(&self.atlas, text),
// The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)),
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
@@ -430,7 +440,7 @@ impl Game<'_> {
}
_ => {
return Err(
"type needs the chat screen (key t tap), the language search or the creative search".into(),
"type needs the chat screen (key t tap), the language search, the creative search or World Options".into(),
);
}
}
@@ -580,6 +590,18 @@ impl Game<'_> {
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
self.physical_keys.insert(key);
// A server's chat input takes the keys first, as remote_chat_key does.
if self.remote_chat_open() {
use winit::keyboard::NamedKey;
let named = match key {
KeyCode::Escape => Some(NamedKey::Escape),
KeyCode::Enter | KeyCode::NumpadEnter => Some(NamedKey::Enter),
KeyCode::Backspace => Some(NamedKey::Backspace),
_ => None,
};
self.remote_chat_input(named, None);
return Ok(());
}
if self.screen == Screen::Chat {
self.chat_key_code(key, None);
return Ok(());
@@ -609,6 +631,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
Screen::CommandBlock => "command-block",
}
}
@@ -168,7 +168,7 @@ impl Game<'_> {
]
.into(),
};
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(id) = registry.id(&state) else {
return;
};
+4 -4
View File
@@ -84,7 +84,7 @@ impl HeartHost for Host<'_> {
impl Game<'_> {
fn heart_state_name(&self, state: BlockStateId) -> String {
self.res
self.pack
.assets
.registry
.state(state)
@@ -177,7 +177,7 @@ impl Game<'_> {
}
/// `Creaking.tearDown`: the crumble particles.
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| {
let Some(mut state) = registry
.default_state(name)
@@ -229,7 +229,7 @@ impl Game<'_> {
});
let state = self.world.block(key.0, key.1, key.2);
let natural = self
.res
.pack
.assets
.registry
.state(state)
@@ -297,7 +297,7 @@ impl Game<'_> {
/// entity (`newBlockEntity`) the first time their chunk is seen.
fn scan_for_hearts(&mut self) {
let Some(heart) = self
.res
.pack
.assets
.registry
.default_state("minecraft:creaking_heart")
+85 -15
View File
@@ -378,13 +378,14 @@ impl Game<'_> {
let (rain, thunder) = self.world.weather.levels(1.0);
MobWorld {
world: &self.world,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
facts: &self.res.facts,
movement: &self.motion.blocks,
collision: self.collision,
data: &self.res.mob_data,
player: self.player_view(),
others,
others_grid: None,
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
game_time: self.world.game_time,
day_time: self.world.day_time,
@@ -514,6 +515,13 @@ impl Game<'_> {
let mut dead = Vec::new();
let mut died = std::mem::take(&mut self.died);
let ticking = self.entity_ticking_area();
// With guests on, each mob sees its nearest player (game/lan_mobs.rs).
let guests = self.lan_guest_views();
let mut bindings = match self.lan.as_mut() {
Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players),
_ => Default::default(),
};
let mut guest_events = Vec::new();
let level_random;
{
// The level random, lent to the mobs (brain behaviours draw from
@@ -521,9 +529,28 @@ impl Game<'_> {
let mut scratch = self.world.random.clone();
let mut pushes = Vec::new();
let mut keep = Vec::with_capacity(mobs.len());
let mut grid =
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
for i in 0..mobs.len() {
let w = self.mob_world_base(&snapshot);
let mut w = self.mob_world_base(&snapshot);
w.others_grid = Some(&grid);
let m = &mut mobs[i];
let seen_guest = if guests.is_empty() {
None
} else {
let bound = bindings.get(&m.id).copied();
let conn = super::lan_mobs::player_for(m, w.player.as_ref(), &guests, bound);
match conn {
Some(conn) => {
bindings.insert(m.id, conn);
w.player = guests.iter().find(|g| g.0 == conn).map(|g| g.1.clone());
}
None => {
bindings.remove(&m.id);
}
}
conn
};
if !w
.world
.loaded(m.position.x.floor() as i32, m.position.z.floor() as i32)
@@ -547,6 +574,16 @@ impl Game<'_> {
let from = events.len();
let kept = m.tick(&w, &mut scratch, &mut events);
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
if let Some(conn) = seen_guest {
let mut k = from;
while k < events.len() {
if super::lan_mobs::acts_on_player(&events[k]) {
guest_events.push((conn, events.remove(k)));
} else {
k += 1;
}
}
}
// Killed during its own tick (drowning, burning, falling...).
if !m.alive() && !m.removed && died.insert(m.id) {
dead.push(m.clone());
@@ -559,6 +596,7 @@ impl Game<'_> {
// after this mob see it as it is now.
snapshot[i] = seen(m, uuid);
snapshot[i].alive &= kept;
grid.update(i, snapshot[i].bounds);
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
}
let mut flags = keep.into_iter();
@@ -569,6 +607,12 @@ impl Game<'_> {
level_random = scratch;
}
self.world.random = level_random;
if let Some(host) = self.lan.as_mut()
&& !guests.is_empty()
{
bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id));
host.mob_players = bindings;
}
self.mobs.append(&mut mobs);
self.died = died;
self.sync_riders();
@@ -581,6 +625,7 @@ impl Game<'_> {
self.mob_died(&m);
}
self.handle_mob_events(events)?;
self.lan_guest_mob_events(guest_events);
self.tick_projectiles()?;
self.tick_fangs();
self.tick_allays();
@@ -950,7 +995,7 @@ impl Game<'_> {
0.8,
);
}
if let Some(state) = self.res.assets.registry.default_state(name) {
if let Some(state) = self.pack.assets.registry.default_state(name) {
self.world.set(pos[0], pos[1], pos[2], state)?;
}
}
@@ -959,7 +1004,7 @@ impl Game<'_> {
self.destroy_particles(pos, old);
if drop {
let drops = self.res.items.block_drops_in(
self.res.assets.registry,
self.pack.assets.registry,
old,
None,
&mut self.world.random,
@@ -1337,7 +1382,12 @@ impl Game<'_> {
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
self.mob_hits_player(amount, from, kind);
}
fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) -> bool {
pub(super) fn mob_hits_player(
&mut self,
amount: f32,
from: [f64; 3],
damage_type: &str,
) -> bool {
if self.creative {
return false;
}
@@ -1350,8 +1400,8 @@ impl Game<'_> {
.is_some_and(|t| t.contains(damage_type));
let blocking = self.player_blocking(Some(from), damage_type, false);
let raised = blocking.is_some();
// Melee: the attacker stands at `from`.
let attacker = (!projectile)
// Melee: the attacker stands at `from` (another player's hit has no mob behind it).
let attacker = (!projectile && damage_type != "minecraft:player_attack")
.then(|| {
self.mobs
.iter()
@@ -1536,12 +1586,24 @@ impl Game<'_> {
// Arrows also hit minecarts (VehicleEntity is pickable).
let mut arrow_targets = targets.clone();
arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds())));
// Mobs' projectiles also hit the guests (game/lan_mobs.rs).
let guests = self.lan_projectile_targets();
let mut arrow_targets_guests = arrow_targets.clone();
arrow_targets_guests.extend(guests.iter().copied());
let mut targets_guests = targets.clone();
targets_guests.extend(guests);
let pw = ProjWorld { w: &w, targets };
let pw_guests = ProjWorld {
w: &w,
targets: targets_guests,
};
projectiles.retain_mut(|p| {
let (keep, hit) = if p.arrow.is_some() {
horizon_client::arrows::tick(p, &scene, &arrow_targets)
} else {
p.tick(&pw)
let mob_shot = !matches!(p.owner, Some(Who::Player));
let (keep, hit) = match (p.arrow.is_some(), mob_shot) {
(true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets),
(true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests),
(false, false) => p.tick(&pw),
(false, true) => p.tick(&pw_guests),
};
if let Some(a) = p.arrow.as_mut() {
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
@@ -1690,7 +1752,7 @@ impl Game<'_> {
) -> horizon_client::arrows::ArrowScene<'s, 's> {
horizon_client::arrows::ArrowScene {
world: &self.world,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
facts: &self.res.facts,
collision: self.collision,
fluids: &self.motion.fluids,
@@ -1722,7 +1784,7 @@ impl Game<'_> {
self.creatures.projectiles.push(arrow);
}
}
fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
self.combat.projectile_owner = match p.owner {
Some(Who::Mob(id)) => Some(id),
_ => None,
@@ -1731,6 +1793,14 @@ impl Game<'_> {
Hit::Entity { at, .. } | Hit::Block { at, .. } => at,
Hit::None => return Ok(()),
};
if let Hit::Entity {
who: Who::Mob(id),
at,
} = hit
&& self.lan_projectile_hit(p, id, at)
{
return Ok(());
}
if matches!(
p.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
@@ -1938,7 +2008,7 @@ impl Game<'_> {
.facts
.is_air(self.world.block(fire[0], fire[1], fire[2]))
&& let Some(state) =
self.res.assets.registry.default_state("minecraft:fire")
self.pack.assets.registry.default_state("minecraft:fire")
{
self.world.set(fire[0], fire[1], fire[2], state)?;
}
@@ -2701,7 +2771,7 @@ impl Game<'_> {
}
/// Mob models and projectiles for the entity pass.
pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let scale = f64::from(self.settings.entity_distance);
for mob in &self.mobs {
+2 -2
View File
@@ -83,7 +83,7 @@ impl Game<'_> {
// (EditBox.keyPressed); releases still reach KeyboardHandler.
let typing = matches!(
self.screen,
Screen::Chat | Screen::Options | Screen::WorldOptions
Screen::Chat | Screen::Options | Screen::WorldOptions | Screen::CommandBlock
) || self.sign_edit.is_some()
|| self.book.is_some()
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
@@ -423,7 +423,7 @@ impl Game<'_> {
));
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width);
let charts = self.debug_charts.draw(
&atlas.font,
@@ -0,0 +1,152 @@
//! Decorated pots, which Horizon keeps as loaded (the chunk's saved block
//! entities): the loot table a trial chamber pot holds, rolled into its item
//! the first time the item is read (`RandomizableContainer.unpackLootTable`),
//! and `DecoratedPotBlock.useItemOn` / `useWithoutItem`.
use super::{Game, spill};
use horizon_client::{
first_person::Hand,
items::ItemStack,
mobs::Who,
particles::{ParticleOptions, ParticleType},
random_sequences::RandomSequences,
save,
};
use horizon_core::random::LegacyRandom;
use horizon_world::{loot::LootData, nbt::Tag};
/// `DecoratedPotBlockEntity.WobbleStyle` ordinals.
const WOBBLE_POSITIVE: i32 = 0;
const WOBBLE_NEGATIVE: i32 = 1;
/// `RandomizableContainer.unpackLootTable(null)` on a pot's saved tag: the
/// loot table, if any, is removed and `LootTable.fill` puts its roll in
/// `item`. The roll draws from `LootTableSeed`, else the table's random
/// sequence, else the level random (`LootContext.Builder.create`).
pub(super) fn unpack_loot(
tag: &mut Tag,
loot: Option<&LootData>,
random: &mut LegacyRandom,
sequences: &mut RandomSequences,
world_seed: i64,
) {
let Tag::Compound(map) = tag else {
return;
};
let Some(Tag::String(table)) = map.remove(&"LootTable".into()) else {
return;
};
let seed = match map.remove(&"LootTableSeed".into()) {
Some(Tag::Long(seed)) => seed,
_ => 0,
};
map.remove(&"item".into());
let Some(loot) = loot else {
return;
};
let table = table.to_string_lossy();
// No origin biome: the pot tables have no location checks.
let slots = if seed != 0 {
loot.fill(&table, seed, 1, None)
} else if let Some(sequence) = loot.random_sequence(&table) {
loot.fill_with(&table, sequences.get(sequence, world_seed), 1, None)
} else {
loot.fill_with(&table, random, 1, None)
};
if let Some(stack) = slots.into_iter().next().flatten() {
let item = horizon_client::structure_blocks::loot_item_with_components(&stack);
map.insert("item".into(), save::item_to_nbt(&item));
}
}
impl Game<'_> {
/// The pot's saved tag at `pos` with its loot unpacked (a new one for a
/// pot without), or None when no pot is there.
fn pot_tag(&mut self, pos: [i32; 3]) -> Option<Tag> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if &*self.res.facts.get(state).name != "minecraft:decorated_pot" {
return None;
}
let mut tag = spill::saved_entity(&self.world, pos).unwrap_or_else(|| {
Tag::compound([
("id", Tag::String("minecraft:decorated_pot".into())),
("x", Tag::Int(pos[0])),
("y", Tag::Int(pos[1])),
("z", Tag::Int(pos[2])),
])
});
let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
unpack_loot(
&mut tag,
loot.as_deref(),
&mut self.world.random,
&mut self.rand_sequences,
self.level.seed,
);
Some(tag)
}
/// `DecoratedPotBlock.useItemOn` with `held`, then `useWithoutItem` on the
/// main hand's turn: true when the pot took the click.
pub(super) fn use_decorated_pot(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool {
let Some(mut tag) = self.pot_tag(pos) else {
return false;
};
let mut pot_item = tag.get("item").and_then(save::item_from_nbt);
let insertable = held.filter(|stack| match &pot_item {
None => true,
Some(p) => p.same_item_same_components(stack) && p.count < self.max_stack(p),
});
let center = pos.map(|v| f64::from(v) + 0.5);
let Some(stack) = insertable else {
spill::put_saved_entity(&mut self.world, pos, tag);
// TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem.
if self.hand != Hand::Main {
return false;
}
self.audio.play(
"minecraft:block.decorated_pot.insert_fail",
Some(center),
1.0,
1.0,
);
self.block_entity_event(pos, 1, WOBBLE_NEGATIVE);
self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None);
return true;
};
let stack = stack.clone();
self.block_entity_event(pos, 1, WOBBLE_POSITIVE);
self.stats.add("used", &stack.item, 1);
// consumeAndReturn(1): one item goes in (a creative player keeps theirs).
let inserted = match &mut pot_item {
Some(p) => {
p.count += 1;
p
}
None => pot_item.insert(ItemStack {
count: 1,
..stack.clone()
}),
};
let pitch_bend = inserted.count as f32 / self.max_stack(inserted) as f32;
if let (Tag::Compound(map), Some(item)) = (&mut tag, &pot_item) {
map.insert("item".into(), save::item_to_nbt(item));
}
spill::put_saved_entity(&mut self.world, pos, tag);
self.consume_held();
self.audio.play(
"minecraft:block.decorated_pot.insert",
Some(center),
1.0,
0.7 + 0.5 * pitch_bend,
);
self.particles.send_particles(
&ParticleOptions::simple(ParticleType::DustPlume),
[center[0], f64::from(pos[1]) + 1.2, center[2]],
[0.0; 3],
0.0,
7,
);
self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None);
self.trigger_block("minecraft:item_used_on_block", pos, &stack);
true
}
}
+3 -2
View File
@@ -418,6 +418,7 @@ impl Game<'_> {
enforces_secure_chat: false,
accepts_transfers: props.accepts_transfers,
announce: false,
listen: true,
bypasses_limit: Some(Arc::new(move |uuid| {
bypass_lists
.lock()
@@ -525,7 +526,7 @@ impl Game<'_> {
/// Load the spawn area and find the world spawn as single player does,
/// without keeping a player there.
fn settle_spawn(&mut self) -> Result<()> {
pub(super) fn settle_spawn(&mut self) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(600);
while self.player.is_none() {
self.update_world();
@@ -541,7 +542,7 @@ impl Game<'_> {
/// The chunks to keep loaded: the players' (lan_update_streaming), or
/// the spawn chunk while nobody is online.
fn update_dedicated_streaming(&mut self) {
pub(super) fn update_dedicated_streaming(&mut self) {
let center = self
.lan
.as_ref()
@@ -224,7 +224,7 @@ impl Game<'_> {
for p in crafter_positions {
let state = self.world.block(p.0, p.1, p.2);
let triggered = self
.res
.pack
.assets
.registry
.state(state)
+26 -13
View File
@@ -308,7 +308,7 @@ pub(super) fn mob_set_slot(m: &mut Mob, slot: Slot, stack: ItemStack) {
impl Game<'_> {
fn prop(&self, state: BlockStateId, key: &str) -> Option<String> {
self.res
self.pack
.assets
.registry
.state(state)?
@@ -318,11 +318,11 @@ impl Game<'_> {
}
/// The same block with other properties (`withProperty`).
fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
let mut s = self.pack.assets.registry.state(state)?.clone();
for (k, v) in props {
s.properties.insert((*k).to_owned(), (*v).to_owned());
}
self.res.assets.registry.resolve(&s).ok()
self.pack.assets.registry.resolve(&s).ok()
}
fn block_at(&self, p: Pos) -> BlockStateId {
self.world.block(p.0, p.1, p.2)
@@ -933,6 +933,21 @@ impl Game<'_> {
LAUNCH,
),
};
self.shoot_projectile_item(at, dir, &stack, power, uncertainty);
(shrink(stack), event)
}
/// `ProjectileItem.asProjectile` and `Projectile.spawnProjectileUsingShoot`:
/// one of `stack` fired from `at` along `dir`.
pub(super) fn shoot_projectile_item(
&mut self,
at: Vec3,
dir: [f64; 3],
stack: &ItemStack,
power: f32,
uncertainty: f32,
) {
let item = stack.item.to_string();
let one = ItemStack {
count: 1,
..stack.clone()
@@ -967,7 +982,7 @@ impl Game<'_> {
"minecraft:tipped_arrow" => ProjectileKind::Arrow {
base_damage: 2.0,
critical: false,
effect: tipped_effect(&stack),
effect: tipped_effect(stack),
},
"minecraft:fire_charge" | "minecraft:wind_charge" => {
// asProjectile aims with the level's random first; the
@@ -1000,7 +1015,6 @@ impl Game<'_> {
self.creatures.projectiles.push(shot);
}
}
(shrink(stack), event)
}
// ---- entities placed by items ----
@@ -1393,7 +1407,7 @@ impl Game<'_> {
}
};
let skull = self
.res
.pack
.assets
.registry
.default_state("minecraft:wither_skeleton_skull")
@@ -1456,7 +1470,7 @@ impl Game<'_> {
&& self.can_spawn_golem([target.0, target.1, target.2])
{
if let Some(pumpkin) = self
.res
.pack
.assets
.registry
.default_state("minecraft:carved_pumpkin")
@@ -1527,8 +1541,7 @@ impl Game<'_> {
let target = (placed.x, placed.y, placed.z);
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(target, entity);
self.fill_placed_box([target.0, target.1, target.2], &stack);
self.name_placed_container([target.0, target.1, target.2], &stack);
self.apply_placed_item([target.0, target.1, target.2], &stack, false);
}
self.process_level_events()?;
Ok((shrink(stack), CLICK))
@@ -2033,10 +2046,10 @@ impl Game<'_> {
return None;
}
let twin = format!("minecraft:waxed_{n}");
let mut s = self.res.assets.registry.state(state)?.clone();
self.res.assets.registry.default_state(&twin)?;
let mut s = self.pack.assets.registry.state(state)?.clone();
self.pack.assets.registry.default_state(&twin)?;
s.name = twin;
self.res.assets.registry.resolve(&s).ok()
self.pack.assets.registry.resolve(&s).ok()
});
let Some(waxed) =
waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod"))
@@ -2095,7 +2108,7 @@ impl Game<'_> {
1.0,
);
self.post_block_game_event("minecraft:fluid_place", [pos.0, pos.1, pos.2], None, None);
if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") {
if let Some(mud) = self.pack.assets.registry.default_state("minecraft:mud") {
self.level_set([target.0, target.1, target.2], mud)?;
}
let bottle = ItemStack::new("minecraft:glass_bottle", 1);
+8 -16
View File
@@ -582,7 +582,7 @@ impl Game<'_> {
}
/// `EndCrystal.tick`: the time and the fire below it in the End.
fn tick_crystals(&mut self) {
let fire = self.res.assets.registry.default_state("minecraft:fire");
let fire = self.pack.assets.registry.default_state("minecraft:fire");
for i in 0..self.crystals.len() {
self.crystals[i].time += 1;
let p = self.crystals[i].position;
@@ -1702,7 +1702,7 @@ impl Game<'_> {
}
if !self.fight.previously_killed
&& let Some(egg) = self
.res
.pack
.assets
.registry
.default_state("minecraft:dragon_egg")
@@ -1866,9 +1866,9 @@ impl Game<'_> {
batch.width as i32,
batch.height as i32,
&bars,
&self.res.atlas.font,
&self.atlas.font,
);
hud_layout::paint(batch, &self.res.atlas, &draws);
hud_layout::paint(batch, &self.atlas, &draws);
}
/// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`,
/// with `setCreateWorldFog`).
@@ -1906,13 +1906,7 @@ impl Game<'_> {
return;
};
let a = alpha as f32;
let sprite = |n: &str| {
self.res
.atlas
.sprites
.get(n)
.map(|r| [r.u0, r.v0, r.u1, r.v1])
};
let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let (Some(skin), Some(eyes)) = (
sprite("entity/enderdragon/dragon"),
sprite("entity/enderdragon/dragon_eyes"),
@@ -2078,7 +2072,7 @@ impl Game<'_> {
}
/// `submitRays`: the death rays from a fixed seed, fading in white to magenta.
fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec<Vertex>) {
let white = self.res.atlas.font.white();
let white = self.atlas.font.white();
let uv = [white.u0, white.v0];
let over = if t > 0.8 {
((t - 0.8) / 0.2).min(1.0)
@@ -2134,7 +2128,6 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let Some(s) = self
.res
.atlas
.sprites
.get("entity/end_crystal/end_crystal_beam")
@@ -2196,7 +2189,6 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let Some(s) = self
.res
.atlas
.sprites
.get("entity/enderdragon/dragon_fireball")
@@ -2610,7 +2602,7 @@ impl Game<'_> {
/// and grown again with a guarded crystal.
fn rebuild_spike(&mut self, spike: &horizon_world::worldgen::end_spike::EndSpike) {
let (cx, cz, h) = (spike.center_x, spike.center_z, spike.height);
let air = self.res.assets.registry.default_state("minecraft:air");
let air = self.pack.assets.registry.default_state("minecraft:air");
let Some(air) = air else {
return;
};
@@ -2685,7 +2677,7 @@ impl Game<'_> {
}
/// Iron bars connected north, south, west and east.
fn set_bars(&mut self, pos: [i32; 3], sides: [bool; 4]) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(mut state) = registry
.default_state("minecraft:iron_bars")
.and_then(|d| registry.state(d).cloned())
+6 -8
View File
@@ -142,7 +142,7 @@ impl Game<'_> {
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
pub(super) fn end_sky_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::with_capacity(6 * 256 * 4);
let Some(r) = self.res.atlas.sprites.get("environment/end_sky").copied() else {
let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else {
return out;
};
use std::f32::consts::FRAC_PI_2;
@@ -184,7 +184,6 @@ impl Game<'_> {
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
if intensity > 1e-5
&& let Some(r) = self
.res
.atlas
.sprites
.get("environment/celestial/end_flash")
@@ -237,7 +236,7 @@ impl Game<'_> {
if &*stack.item != "minecraft:ender_eye" {
return Ok(false);
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let target = self.pick().and_then(|hit| {
let state = registry.state(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))?;
(state.name == "minecraft:end_portal_frame").then(|| (hit, state.clone()))
@@ -303,7 +302,7 @@ impl Game<'_> {
/// ring (corners free) of filled frames, all facing the centre or all
/// facing away from it. Returns the centre of the 3×3 opening.
fn portal_ring_center(&self, frame: [i32; 3]) -> Option<[i32; 3]> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
// (offset from the centre, facing when the frames face the centre)
let mut ring = Vec::with_capacity(12);
for i in -1..=1 {
@@ -630,7 +629,7 @@ impl Game<'_> {
&[],
)?;
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
for (facing, d) in [
("north", [0, -1]),
("south", [0, 1]),
@@ -898,8 +897,7 @@ impl Game<'_> {
fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let (Some(model), Some(r)) = (
self.crystal_model.as_ref(),
self.res
.atlas
self.atlas
.sprites
.get("entity/end_crystal/end_crystal")
.copied(),
@@ -1052,7 +1050,7 @@ impl Game<'_> {
/// ThrownItemRenderer: the ender eye item facing the camera.
fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let Some(r) = self.res.atlas.sprites.get("item/ender_eye").copied() else {
let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else {
return;
};
let alpha = self.clock.fraction();
+1 -1
View File
@@ -511,7 +511,7 @@ impl Game<'_> {
// random sequence.
let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius);
let drops = self.res.items.block_drops_exploded(
self.res.assets.registry,
self.pack.assets.registry,
state,
None,
&dynamic,
+4 -4
View File
@@ -193,10 +193,10 @@ impl Game<'_> {
if !self.extras.minimap.compose(view) {
return;
}
let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
return;
};
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -242,7 +242,7 @@ impl Game<'_> {
let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size));
let visible = |corner| !(self.debug && corner == Corner::TopLeft);
let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height());
let atlas = &self.res.atlas;
let atlas = &self.atlas;
if let Some(view) = self.minimap_view()
&& visible(map_corner)
&& !self.extras.minimap.image.is_empty()
@@ -286,7 +286,7 @@ impl Game<'_> {
use_: self.extras.mouse[1],
cps,
};
extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k);
extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k);
}
if mod_panels {
self.draw_mod_panels(batch, &mut corners);
-1
View File
@@ -108,7 +108,6 @@ impl Game<'_> {
return;
};
let Some(r) = self
.res
.atlas
.sprites
.get("entity/illager/evoker_fangs")
@@ -565,7 +565,6 @@ impl Game<'_> {
return;
};
let Some(r) = self
.res
.atlas
.sprites
.get("entity/fishing/fishing_hook")
+1 -1
View File
@@ -171,6 +171,6 @@ impl Game<'_> {
}
let draws =
hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale);
hud_layout::paint(batch, &self.res.atlas, &draws);
hud_layout::paint(batch, &self.atlas, &draws);
}
}
+1 -1
View File
@@ -301,7 +301,7 @@ impl Game<'_> {
}
/// ItemFrameRenderer: the frame model, then the item half size on its face.
pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let sprites = &self.res.atlas.sprites;
let sprites = &self.atlas.sprites;
let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new();
let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new();
for f in &self.item_frames {
@@ -0,0 +1,593 @@
//! InWorldGameRulesScreen (AbstractGameRulesScreen), opened from World
//! Options: the rules by category under a search box, a switch or a number
//! box each, and Done sending the changed ones (ServerboundSetGameRulePacket).
//! Leaving with changes asks first (ConfirmScreen).
use horizon_client::{
font::Font,
gamerules::{self, GameRules, RULES, Rule, Value},
hud::{HudAtlas, HudBatch},
lang,
text::{Style, Text, named_color},
ui::{self, EditBox},
};
/// HeaderAndFooterLayout(12 + 9 + 15, 33): the title over the search box.
const HEADER: f32 = 36.0;
const FOOTER: f32 = 33.0;
/// RuleList: 24 pixel entries in AbstractSelectionList's 220 pixel rows.
const ROW: f32 = 24.0;
const ROW_WIDTH: f32 = 220.0;
const SEARCH_WIDTH: f32 = 200.0;
/// EditBox text colours (`hud::rgba` order, ABGR): IntegerRuleEntry's valid
/// (-2039584) and invalid (-65536).
const VALID: u32 = 0xFFE0_E0E0;
const INVALID: u32 = 0xFF00_00FF;
#[derive(Clone, Copy)]
enum Row {
Category(&'static str),
Rule(&'static Rule),
}
/// What a click or Escape asks of World Options.
#[derive(Debug, PartialEq)]
pub(super) enum Exit {
/// Done: the rules that changed.
Apply(Vec<(&'static str, Value)>),
/// Cancel, or discarding the changes.
Discard,
}
pub(super) struct RulesScreen {
search: EditBox,
values: GameRules,
initial: GameRules,
/// IntegerRuleEntry's boxes, by rule.
numbers: Vec<(&'static str, EditBox)>,
scroll: f32,
/// ConfirmScreen "Game Rule Changes" in its place.
confirm: bool,
}
fn name_key(r: &Rule) -> String {
format!("gamerule.minecraft.{}", r.name)
}
fn category_key(category: &str) -> String {
format!("gamerule.category.minecraft.{category}")
}
/// GameRule.deserialize of an integer rule: Brigadier's readInt (digits,
/// '.' and '-' only, nothing after), then the rule's range.
fn parse(r: &Rule, s: &str) -> Option<i32> {
let number = !s.is_empty()
&& s.chars()
.all(|c| c.is_ascii_digit() || c == '-' || c == '.');
number
.then(|| s.parse::<i32>().ok())
.flatten()
.filter(|v| (r.min..=r.max).contains(v))
}
fn widest(font: &Font, lines: &[Text]) -> f32 {
lines.iter().map(|l| font.width_text(l)).fold(0.0, f32::max)
}
fn lines(font: &Font, t: &Text, width: f32) -> Vec<Text> {
font.split_lines(t, width)
.into_iter()
.map(|(line, _)| line)
.collect()
}
fn row_left(w: f32) -> f32 {
(w / 2.0).trunc() - ROW_WIDTH / 2.0
}
/// A rule's switch or box: 44 by 20, 45 from the entry content's right.
fn control_x(w: f32) -> f32 {
row_left(w) + 2.0 + (ROW_WIDTH - 4.0) - 45.0
}
/// The header's LinearLayout (title, 4, search box) centred in its 36 pixels.
fn search_at(w: f32) -> (f32, f32) {
(((w - SEARCH_WIDTH) / 2.0).trunc(), 4.0 + 9.0 + 4.0)
}
/// The footer's Done and Cancel, 150 wide and 8 apart.
fn footer(w: f32, h: f32) -> [(f32, f32); 2] {
let x = ((w - 308.0) / 2.0).trunc();
[(x, h - FOOTER + 6.0), (x + 158.0, h - FOOTER + 6.0)]
}
fn yellow() -> u32 {
named_color("yellow").unwrap_or(0xFFFF55)
}
/// ConfirmScreen: the title, the message (at most `width - 50` wide), and
/// Yes / No 16 below, 4 apart, all centred.
struct Confirm {
lines: Vec<(Text, f32, f32)>,
buttons: [(f32, f32); 2],
}
impl Confirm {
fn new(font: &Font, (w, h): (f32, f32)) -> Self {
let title = Text::translate("editGamerule.inGame.discardChanges.title", &[]);
let message = Text::translate("editGamerule.inGame.discardChanges.message", &[]);
let message: Vec<Text> = lines(font, &message, w - 50.0)
.into_iter()
.take(15)
.collect();
let (tw, mw) = (font.width_text(&title), widest(font, &message));
let mh = 9.0 * message.len() as f32;
let col = tw.max(mw).max(304.0);
let total = 9.0 + 8.0 + mh + 8.0 + 36.0;
let (lx, ly) = (((w - col) / 2.0).trunc(), ((h - total) / 2.0).trunc());
let cell = |cw: f32| lx + ((col - cw) / 2.0).trunc();
let mid = cell(mw) + (mw / 2.0).trunc();
let mut out = vec![(title, cell(tw), ly)];
for (i, line) in message.into_iter().enumerate() {
let x = mid - (font.width_text(&line) / 2.0).trunc();
out.push((line, x, ly + 17.0 + 9.0 * i as f32));
}
let (bx, by) = (cell(304.0), ly + 9.0 + 8.0 + mh + 8.0 + 16.0);
Self {
lines: out,
buttons: [(bx, by), (bx + 154.0, by)],
}
}
}
impl RulesScreen {
pub(super) fn new(rules: &GameRules) -> Self {
// setInitialFocus: the search box.
let search = EditBox::new(0.0, 0.0, SEARCH_WIDTH, 15.0);
let numbers = RULES
.iter()
.filter(|r| matches!(r.default, Value::Int(_)))
.map(|r| {
let mut b = EditBox::new(0.0, 0.0, 44.0, 20.0);
b.focused = false;
b.set_value(&rules.int(r.name).to_string());
b.text_color = VALID;
(r.name, b)
})
.collect();
Self {
search,
values: rules.clone(),
initial: rules.clone(),
numbers,
scroll: 0.0,
confirm: false,
}
}
/// RuleList.populateChildren: the rules matching the search (id, name,
/// category or description), by category, each sorted by description id.
fn rows(&self) -> Vec<Row> {
let filter = self.search.value.to_lowercase();
let has = |s: &str| s.to_lowercase().contains(&filter);
let mut categories: Vec<(&'static str, Vec<&'static Rule>)> = Vec::new();
for r in RULES {
let key = name_key(r);
let description = format!("{key}.description");
let matches = has(r.name)
|| has(&lang::get(&key))
|| has(&lang::get(&category_key(r.category)))
|| (lang::has(&description) && has(&lang::get(&description)));
if !matches {
continue;
}
match categories.iter_mut().find(|(c, _)| *c == r.category) {
Some((_, rules)) => rules.push(r),
None => categories.push((r.category, vec![r])),
}
}
// By the categories' ids, then the rules' description ids.
categories.sort_by_key(|(c, _)| *c);
categories
.into_iter()
.flat_map(|(c, mut rules)| {
rules.sort_by_key(|r| name_key(r));
std::iter::once(Row::Category(c)).chain(rules.into_iter().map(Row::Rule))
})
.collect()
}
fn max_scroll(rows: usize, h: f32) -> f32 {
(ROW * rows as f32 + 4.0 - (h - HEADER - FOOTER)).max(0.0)
}
/// Entry `i`'s top: 2 under the list's top, less the scroll.
fn row_top(&self, i: usize) -> f32 {
HEADER + 2.0 - self.scroll.trunc() + ROW * i as f32
}
/// getEntryAtPosition: the row under the pointer, inside the list.
fn hovered(&self, rows: usize, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option<usize> {
let left = row_left(w);
let inside = y >= HEADER && y < h - FOOTER && x >= left && x < left + ROW_WIDTH;
let i = ((y - self.row_top(0)) / ROW).floor();
(inside && i >= 0.0 && (i as usize) < rows).then_some(i as usize)
}
fn number(&mut self, name: &str) -> Option<&mut EditBox> {
self.numbers
.iter_mut()
.find(|(n, _)| *n == name)
.map(|(_, b)| b)
}
/// An invalid number disables Done (markInvalid).
fn invalid(&self) -> bool {
self.numbers
.iter()
.any(|(name, b)| gamerules::rule(name).is_none_or(|r| parse(r, &b.value).is_none()))
}
fn changes(&self) -> Vec<(&'static str, Value)> {
RULES
.iter()
.filter_map(|r| {
let value = self.values.get(r.name)?;
(Some(value) != self.initial.get(r.name)).then_some((r.name, value))
})
.collect()
}
/// InWorldGameRulesScreen.onClose: pending changes ask first.
fn close(&mut self) -> Option<Exit> {
if self.changes().is_empty() {
Some(Exit::Discard)
} else {
self.confirm = true;
None
}
}
/// Escape: ConfirmScreen answers no; the rules close.
pub(super) fn escape(&mut self) -> Option<Exit> {
if self.confirm {
self.confirm = false;
None
} else {
self.close()
}
}
/// The mouse wheel (AbstractSelectionList: half an entry a step).
pub(super) fn wheel(&mut self, delta: f32, h: f32) {
if !self.confirm {
let max = Self::max_scroll(self.rows().len(), h);
self.scroll = (self.scroll - delta * ROW / 2.0).clamp(0.0, max);
}
}
fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> {
if self.search.focused {
return Some((None, &mut self.search));
}
self.numbers
.iter_mut()
.find(|(_, b)| b.focused)
.map(|(n, b)| (Some(*n), b))
}
/// The focused box changed: the search filters again from the top; a
/// number sets its rule when valid (IntegerRuleEntry's responder).
fn edited(&mut self, rule: Option<&'static str>) {
let Some(name) = rule else {
self.scroll = 0.0;
return;
};
let Some(r) = gamerules::rule(name) else {
return;
};
let value = self.number(name).map(|b| parse(r, &b.value));
if let Some(Some(v)) = value {
self.values.set(name, Value::Int(v));
}
if let Some(b) = self.number(name) {
b.text_color = if matches!(value, Some(Some(_))) {
VALID
} else {
INVALID
};
}
}
/// Run an edit on the focused box, then its responder.
pub(super) fn edit(&mut self, f: impl FnOnce(&mut EditBox)) {
let Some((rule, b)) = self.focused() else {
return;
};
let before = b.value.clone();
f(b);
if b.value != before {
self.edited(rule);
}
}
pub(super) fn typing(&self) -> bool {
!self.confirm && (self.search.focused || self.numbers.iter().any(|(_, b)| b.focused))
}
/// A left click; Some when the screen closes.
pub(super) fn click(
&mut self,
atlas: &HudAtlas,
cursor: (f32, f32),
size: (f32, f32),
) -> Option<Exit> {
let (w, h) = size;
let on = |x: f32, y: f32, bw: f32, bh: f32| ui::hovered(cursor, x, y, bw, bh);
if self.confirm {
let c = Confirm::new(&atlas.font, size);
let [(yx, yy), (nx, ny)] = c.buttons;
if on(yx, yy, 150.0, 20.0) {
return Some(Exit::Discard);
}
if on(nx, ny, 150.0, 20.0) {
self.confirm = false;
}
return None;
}
let [(dx, dy), (cx, cy)] = footer(w, h);
if on(dx, dy, 150.0, 20.0) && !self.invalid() {
return Some(Exit::Apply(self.changes()));
}
if on(cx, cy, 150.0, 20.0) {
return self.close();
}
// A click moves the focus to the widget under it.
let (sx, sy) = search_at(w);
if on(sx, sy, SEARCH_WIDTH, 15.0) {
self.unfocus();
self.search.focused = true;
self.search.reset_blink();
self.search.click(atlas, cursor.0, false, false);
return None;
}
let rows = self.rows();
let i = self.hovered(rows.len(), cursor, size)?;
let Row::Rule(r) = rows[i] else {
return None;
};
if !on(control_x(w), self.row_top(i) + 2.0, 44.0, 20.0) {
return None;
}
self.unfocus();
match r.default {
Value::Bool(_) => {
let on = self.values.bool(r.name);
self.values.set(r.name, Value::Bool(!on));
}
Value::Int(_) => {
if let Some(b) = self.number(r.name) {
b.focused = true;
b.reset_blink();
b.click(atlas, cursor.0, false, false);
}
}
}
None
}
fn unfocus(&mut self) {
self.search.focused = false;
for (_, b) in &mut self.numbers {
b.focused = false;
}
}
/// Whether a click lands on a button (for its sound).
pub(super) fn clicks_button(
&self,
atlas: &HudAtlas,
cursor: (f32, f32),
size: (f32, f32),
) -> bool {
let (w, h) = size;
let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0);
if self.confirm {
return Confirm::new(&atlas.font, size).buttons.into_iter().any(on);
}
let [done, cancel] = footer(w, h);
if (on(done) && !self.invalid()) || on(cancel) {
return true;
}
let rows = self.rows();
self.hovered(rows.len(), cursor, size).is_some_and(|i| {
matches!(rows[i], Row::Rule(r) if matches!(r.default, Value::Bool(_)))
&& ui::hovered(cursor, control_x(w), self.row_top(i) + 2.0, 44.0, 20.0)
})
}
pub(super) fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) {
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
if self.confirm {
let c = Confirm::new(&atlas.font, (w, h));
for (line, x, y) in &c.lines {
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
}
for ((bx, by), key) in c.buttons.into_iter().zip(["gui.yes", "gui.no"]) {
let hover = ui::hovered(cursor, bx, by, 150.0, 20.0);
let label = Text::translate(key, &[]);
ui::button(batch, atlas, bx, by, 150.0, 20.0, &label, true, hover);
}
return;
}
let rows = self.rows();
self.scroll = self.scroll.clamp(0.0, Self::max_scroll(rows.len(), h));
// RuleList: the in-world list background, its entries clipped to it,
// then the separators and scrollbar.
ui::list_background(batch, atlas, HEADER, h - FOOTER, true);
let first = batch.vertices.len();
let hovered = self.hovered(rows.len(), cursor, (w, h));
let (left, x) = (row_left(w), control_x(w));
for (i, row) in rows.iter().enumerate() {
let top = self.row_top(i);
if top + ROW < HEADER || top > h - FOOTER {
continue;
}
let (cx, cy) = (left + 2.0, top + 2.0);
match *row {
Row::Category(c) => {
// A FocusableTextWidget padded by 4, centred in the entry.
let label = Text::translate(&category_key(c), &[])
.bold()
.underlined()
.with_color(yellow());
let lw = atlas.font.width_text(&label);
let mid = cx + (ROW_WIDTH - 4.0) / 2.0;
let lx = mid - (lw / 2.0).trunc();
batch.text_styled(atlas, &label, lx, cy + 10.0 - 8.0 + 4.0, u32::MAX, true);
}
Row::Rule(r) => {
let name = lines(&atlas.font, &Text::translate(&name_key(r), &[]), 170.0);
match name.as_slice() {
[one] => {
batch.text_styled(atlas, one, cx, cy + 5.0, u32::MAX, true);
}
[one, two, ..] => {
batch.text_styled(atlas, one, cx, cy, u32::MAX, true);
batch.text_styled(atlas, two, cx, cy + 10.0, u32::MAX, true);
}
[] => {}
}
let hover = hovered == Some(i) && ui::hovered(cursor, x, cy, 44.0, 20.0);
match r.default {
Value::Bool(_) => {
let key = if self.values.bool(r.name) {
"options.on"
} else {
"options.off"
};
let label = Text::translate(key, &[]);
ui::button(batch, atlas, x, cy, 44.0, 20.0, &label, true, hover);
}
Value::Int(_) => {
if let Some(b) = self.number(r.name) {
b.x = x;
b.y = cy;
b.draw(batch, atlas, None);
}
}
}
}
}
}
batch.clip_since(first, 0.0, HEADER, w, h - FOOTER);
ui::separators(batch, atlas, HEADER, h - FOOTER, true);
let content = ROW * rows.len() as f32 + 4.0;
let bar_x = left + ROW_WIDTH + 6.0 + 2.0;
ui::scrollbar(
batch,
atlas,
bar_x,
HEADER,
h - FOOTER,
content,
self.scroll.trunc(),
);
// The header: the title centred over the search box.
let title = Text::translate("editGamerule.title", &[]);
let tw = atlas.font.width_text(&title);
let (sx, sy) = search_at(w);
let lw = tw.max(SEARCH_WIDTH);
let lx = ((w - lw) / 2.0).trunc();
batch.text_styled(
atlas,
&title,
lx + ((lw - tw) / 2.0).trunc(),
4.0,
u32::MAX,
true,
);
self.search.x = sx;
self.search.y = sy;
self.search.draw(batch, atlas, None);
if self.search.value.is_empty() && !self.search.focused {
// EditBox.SEARCH_HINT_STYLE: gray and italic.
let hint = Text::translate("gui.game_rule.search", &[]).with_style(&Style {
color: named_color("gray"),
italic: Some(true),
..Style::default()
});
let (hx, hy) = (self.search.text_x(), self.search.text_y());
batch.text_styled(atlas, &hint, hx, hy, u32::MAX, true);
}
let invalid = self.invalid();
for ((bx, by), (key, active)) in footer(w, h)
.into_iter()
.zip([("gui.done", !invalid), ("gui.cancel", true)])
{
let hover = active && ui::hovered(cursor, bx, by, 150.0, 20.0);
let label = Text::translate(key, &[]);
ui::button(batch, atlas, bx, by, 150.0, 20.0, &label, active, hover);
}
// The hovered rule's tooltip: its id, description and default.
if let Some(Row::Rule(r)) = hovered.map(|i| rows[i]) {
let mut tip = vec![Text::literal(r.name).with_color(yellow())];
let description = format!("{}.description", name_key(r));
if lang::has(&description) {
tip.extend(lines(
&atlas.font,
&Text::translate(&description, &[]),
150.0,
));
}
let gray = named_color("gray").unwrap_or(0xAAAAAA);
tip.push(
Text::translate(
"editGamerule.default",
&[Text::literal(r.default.to_string())],
)
.with_color(gray),
);
ui::tooltip(batch, atlas, &tip, cursor);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn box_colours_are_vanillas() {
assert_eq!(VALID, horizon_client::hud::rgba(224, 224, 224, 255));
assert_eq!(INVALID, horizon_client::hud::rgba(255, 0, 0, 255));
}
#[test]
fn numbers_parse_like_brigadier_within_the_rule() {
let r = gamerules::rule("max_snow_accumulation_height").unwrap();
assert_eq!(parse(r, "8"), Some(8));
assert_eq!(parse(r, "9"), None);
assert_eq!(parse(r, "-1"), None);
for s in ["", "+3", " 3", "3 ", "3.0", "x"] {
assert_eq!(parse(r, s), None, "{s:?}");
}
let r = gamerules::rule("fire_spread_radius_around_player").unwrap();
assert_eq!(parse(r, "-1"), Some(-1));
}
#[test]
fn rows_group_categories_and_rules_by_description_id() {
let s = RulesScreen::new(&GameRules::default());
let rows = s.rows();
assert_eq!(rows.len(), RULES.len() + 7);
assert!(matches!(rows[0], Row::Category("chat")));
let categories: Vec<_> = rows
.iter()
.filter_map(|r| match r {
Row::Category(c) => Some(*c),
Row::Rule(_) => None,
})
.collect();
assert_eq!(
categories,
[
"chat", "drops", "misc", "mobs", "player", "spawning", "updates"
]
);
}
#[test]
fn edits_change_rules_and_bad_numbers_hold_done() {
let mut s = RulesScreen::new(&GameRules::default());
assert!(s.changes().is_empty());
s.unfocus();
s.number("random_tick_speed").unwrap().focused = true;
s.edit(|b| b.set_value("10"));
assert_eq!(s.changes(), vec![("random_tick_speed", Value::Int(10))]);
s.edit(|b| b.set_value("ten"));
assert!(s.invalid());
// The last valid value stays, as the responder left it.
assert_eq!(s.changes(), vec![("random_tick_speed", Value::Int(10))]);
// Leaving with changes asks; No returns, Yes discards.
assert_eq!(s.escape(), None);
assert!(s.confirm);
assert_eq!(s.escape(), None);
assert!(!s.confirm);
}
}
@@ -39,7 +39,7 @@ impl Game<'_> {
};
switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32));
let selected = switcher.selected;
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_region(
atlas,
"gui/container/gamemode_switcher",
@@ -62,14 +62,14 @@ impl Game<'_> {
for (index, mode) in MODES.into_iter().enumerate() {
let (x, y) = slot_origin(w, h, index);
batch.sprite(
&self.res.atlas,
&self.atlas,
"gui/sprites/gamemode_switcher/slot",
x as f32,
y as f32,
);
if mode == selected {
batch.sprite(
&self.res.atlas,
&self.atlas,
"gui/sprites/gamemode_switcher/selection",
x as f32,
y as f32,
+18 -2
View File
@@ -6,10 +6,26 @@ use horizon_client::{
items::ItemStack,
mobs::{MobEvent, happy_ghast},
};
use horizon_core::geometry::Vec3;
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::registry::BlockStateId;
impl Game<'_> {
/// Client `EntityGetter.getEntityCollisions`: only solid happy ghasts,
/// excluding the player's own vehicle.
pub(super) fn happy_ghast_player_collisions(&self) -> Vec<Aabb> {
let Some(p) = &self.player else {
return Vec::new();
};
self.mobs
.iter()
.filter(|m| {
m.species() == horizon_client::mobs::Species::HappyGhast
&& Some(m.id) != self.riding
&& happy_ghast::collides_with_player(m, p.position.y)
})
.map(|m| m.bounds())
.collect()
}
/// `HappyGhast.mobInteract`. Returns whether the click was used.
pub(super) fn interact_happy_ghast(&mut self, index: usize, item: &str) -> bool {
let m = &self.mobs[index];
@@ -94,7 +110,7 @@ impl Game<'_> {
f64::from(pos[2]) + 0.5,
];
let facing = self
.res
.pack
.assets
.registry
.state(state)
+1 -1
View File
@@ -146,7 +146,7 @@ impl Game<'_> {
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 registry = self.pack.assets.registry;
let facing = registry
.state(pumpkin)
.and_then(|s| s.properties.get("facing").cloned())
+1 -1
View File
@@ -15,7 +15,7 @@ impl Game<'_> {
}
let dir = self.options.resources.join("worldgen");
let started = std::time::Instant::now();
let features = vanillagen::shared_data(&dir, self.res.assets.registry)
let features = vanillagen::shared_data(&dir, self.pack.assets.registry)
.map_err(|e| e.to_string())
.and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string()));
match features {
+2 -1
View File
@@ -143,6 +143,7 @@ impl Game<'_> {
|| before(self.cart_hit().map(|h| h.1))
|| before(self.dragon_hit().map(|h| h.1))
|| before(self.mob_hit().map(|h| h.1))
|| before(self.guest_hit().map(|h| h.1))
}
/// `LocalPlayer.isHandsBusy`: paddling a boat.
fn hands_busy(&self) -> bool {
@@ -256,7 +257,7 @@ impl Game<'_> {
.or_else(|| self.held());
if let Some(stack) = active {
let components = self
.res
.pack
.item_renderer
.models
.components(&horizon_client::item_render::stack_view(stack));
@@ -72,7 +72,7 @@ impl Game<'_> {
fn spawn_columns(&self) -> Columns<'_, '_> {
Columns {
world: &self.world,
properties: &self.res.assets.properties,
properties: &self.pack.assets.properties,
binding: self.collision,
}
}
@@ -82,7 +82,7 @@ impl Game<'_> {
horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| {
horizon_client::flatgen::FlatTerrain::from_settings(
&s,
self.res.assets.registry,
self.pack.assets.registry,
&self.res.biomes,
)
})
@@ -107,7 +107,6 @@ impl Game<'_> {
None => *self.spawn_origin.insert(self.spawn_origin()?),
};
while let Some((dx, dz)) = self.spawn_spiral.current() {
self.spawn_search = self.spawn_spiral.steps() as u32;
if self.spawn_spiral.tested() {
let (cx, cz) = (ox + dx, oz + dz);
if !self.streaming.is_lit(cx, cz) {
@@ -0,0 +1,289 @@
//! The integrated server (`IntegratedServer`): single player's world runs on
//! its own "Server thread", as vanilla's does, and the window joins it as a
//! player through memory, so a world tick never holds up a frame.
//!
//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the
//! player joins as a network player, and the server side of a network player
//! does not do everything single player does yet. Worlds whose player is
//! outside the Overworld open the usual way, since network players stay in
//! the Overworld so far.
use super::{
Dim, Game, Options, PackResources, Resources,
lan::{LanSettings, Owner},
};
use horizon_client::{
Result,
audio::Audio,
hud::HudAtlas,
lan::{MAX_PLAYERS, NetConfig, hub::HubConfig},
save::Level,
settings::Settings,
title::WorldOptions,
};
use horizon_protocol::connection::Pipe;
use horizon_protocol::{crypto::offline_uuid, text::translatable};
use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{Sender, channel},
},
thread::JoinHandle,
time::{Duration, Instant},
};
/// What the window tells its server thread.
#[derive(Default)]
struct Flags {
/// `Minecraft.pause`: a single-player pause screen is open.
paused: AtomicBool,
stop: AtomicBool,
}
/// The window's handle on its server thread.
pub(super) struct Integrated {
flags: Arc<Flags>,
thread: Option<JoinHandle<()>>,
}
impl Integrated {
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
}
/// `IntegratedServer.halt(true)`: returns once the world is saved and let go.
pub fn stop(mut self) {
self.halt();
}
fn halt(&mut self) {
self.flags.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for Integrated {
fn drop(&mut self) {
self.halt();
}
}
/// The world to open and the player who owns it.
struct Launch {
folder: String,
name: Option<String>,
seed: Option<i64>,
creative: bool,
create: Option<WorldOptions>,
/// The window's profile: the only one let in, and the world's player.
owner: u128,
}
/// Whether this world opens on a server thread: asked for, and its player
/// (if any yet) in the Overworld.
pub(super) fn wanted(options: &Options, world: &Path) -> bool {
options.server_thread
&& options.dedicated.is_none()
&& Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld)
}
impl Game<'_> {
/// `Minecraft.doWorldLoad`: start the server thread on the world, wait
/// until it can be joined, then join it through memory.
pub(super) fn open_integrated(
&mut self,
folder: &str,
name: Option<&str>,
seed: Option<i64>,
creative: bool,
create: Option<&WorldOptions>,
) -> Result<()> {
let auth = horizon_client::auth::current();
let player = auth
.as_ref()
.map_or_else(|| self.options.player_name(), |a| a.name.clone());
let launch = Launch {
folder: folder.to_owned(),
name: name.map(str::to_owned),
seed,
creative,
create: create.cloned(),
// An offline-mode server names its players by their offline profile.
owner: offline_uuid(&player),
};
let mut options = self.options.clone();
// A server without a console: no local player, no window, no control socket.
options.dedicated = Some(Vec::new());
options.server_thread = false;
options.integrated = true;
options.control = None;
options.benchmark = None;
options.frames = None;
options.world_frames = None;
options.report = None;
options.server = None;
options.world = None;
options.dev_mods.clear();
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
let (ready_tx, ready) = channel();
let server_flags = flags.clone();
let thread = std::thread::Builder::new()
.name("Server thread".into())
.spawn(move || {
let result = serve(
&res,
pack,
options,
settings,
launch,
&server_flags,
&ready_tx,
);
if let Err(e) = result {
log::error!("Horizon: integrated server: {e}");
let _ = ready_tx.send(Err(e.to_string()));
}
})?;
let handle = Integrated {
flags,
thread: Some(thread),
};
let pipe = match ready.recv() {
Ok(Ok(pipe)) => pipe,
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err("the integrated server stopped".into()),
};
self.connect_local(pipe, &player)?;
self.integrated = Some(handle);
Ok(())
}
/// The server thread's loop (`MinecraftServer.runServer`): 20 ticks a
/// second, the world held while the window is paused.
fn run_integrated(
&mut self,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<Pipe, String>>,
) -> Result<()> {
self.open_world(
&launch.folder,
launch.name.as_deref(),
launch.seed,
launch.creative,
launch.create.as_ref(),
)?;
let saved = Box::new(self.level.clone());
let view_distance = self.settings.render_distance.clamp(2, 32);
let config = HubConfig {
default_game_mode: self.level.mode(),
guest_commands: true,
force_game_mode: false,
hardcore: self.level.hardcore,
view_distance,
simulation_distance: self.settings.simulation_distance.clamp(2, 32),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
// No player of its own: the hub runs without a host.
dedicated: true,
};
let owner = launch.owner;
let net = NetConfig {
// No network until it is opened to the LAN.
listen: false,
// A memory connection is not compressed (`Connection.isMemoryConnection`).
compression_threshold: -1,
enable_status: false,
announce: false,
gate: Some(Arc::new(move |_, uuid, _| {
(uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[]))
})),
..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS)
};
let settings = LanSettings {
port: 0,
guest_commands: true,
force_game_mode: false,
};
self.lan_host(settings, net, config, None)?;
let commands = self.allow_commands();
let pipe = {
let host = self
.lan
.as_mut()
.ok_or("the integrated server did not start")?;
// The owner is an operator when the world allows commands
// (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`).
host.hub.ops.insert(owner, if commands { 4 } else { 0 });
host.owner = Some(Owner {
uuid: owner,
saved: Some(saved),
});
host.hub.lan.connect_local()?
};
let _ = ready.send(Ok(pipe));
self.settle_spawn()?;
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
// Only the connections run.
self.tick_lan();
} else {
self.tick()?;
}
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
let now = Instant::now();
if next > now {
std::thread::sleep(next - now);
} else if now - next > Duration::from_secs(2) {
next = now;
}
}
self.stop_integrated()
}
/// `MinecraftServer.stopServer`: the players are saved and sent away,
/// then the world is saved.
fn stop_integrated(&mut self) -> Result<()> {
if let Some(mut host) = self.lan.take() {
for g in &host.hub.guests {
self.save_guest(&host, g);
}
let conns: Vec<u32> = host.hub.guests.iter().map(|g| g.conn).collect();
for conn in conns {
host.hub.kick(
conn,
translatable("multiplayer.disconnect.server_shutdown", &[]),
);
}
self.lan = Some(host);
}
std::thread::sleep(Duration::from_millis(100));
self.save_game()?;
self.lan_close(false);
self.save.flush();
self.session_lock = None;
Ok(())
}
}
/// The server thread: a game of its own over the shared resources.
fn serve(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<Pipe, String>>,
) -> Result<()> {
let atlas = HudAtlas::build(&options.resources)?;
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, atlas, options, settings, audio)?;
server.run_integrated(launch, flags, ready)
}
+11 -11
View File
@@ -31,7 +31,7 @@ impl ItemEnv for Env<'_, '_> {
}
fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
self.game
.res
.pack
.item_renderer
.grass_color(temperature, downfall)
}
@@ -43,7 +43,7 @@ impl ItemEnv for Env<'_, '_> {
else {
return 0.0;
};
let prototypes = &self.game.res.item_renderer.models.prototypes;
let prototypes = &self.game.pack.item_renderer.models.prototypes;
let mut total = 0.0f64;
for item in items {
let id = item["id"].as_str().unwrap_or("");
@@ -216,7 +216,7 @@ impl Game<'_> {
&& self.inventory.get(slot).and_then(Option::as_ref) == Some(stack)
{
let view = item_render::stack_view(stack);
let duration = use_duration(&self.res.item_renderer.models.components(&view));
let duration = use_duration(&self.pack.item_renderer.models.components(&view));
owner.using_this_item = true;
owner.use_duration = duration;
owner.use_item_remaining_ticks = duration - ticks as i32;
@@ -239,7 +239,7 @@ impl Game<'_> {
seed: i32,
) -> ItemRenderState {
let level = self.item_level();
self.res.item_renderer.resolve(
self.pack.item_renderer.resolve(
&item_render::stack_view(stack),
display,
owner,
@@ -254,8 +254,8 @@ impl Game<'_> {
let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0);
item_render::gui::draw(
&state,
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.item_host(),
batch,
x,
@@ -278,8 +278,8 @@ impl Game<'_> {
lights: Some(diffuse_lights(self.dim == Dim::Nether)),
};
state.submit(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
@@ -299,8 +299,8 @@ impl Game<'_> {
lights: None,
};
state.submit(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
@@ -360,7 +360,7 @@ impl Game<'_> {
(q.y + 0.1).floor() as i32,
q.z.floor() as i32,
);
let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item))
let seed = i64::from(self.pack.item_renderer.item_id(&item.stack.item))
+ i64::from(item.stack.damage);
for copy in item_render::cluster_poses(
&state,
+1 -1
View File
@@ -21,7 +21,7 @@ impl Game<'_> {
}
fn set_has_record(&mut self, pos: [i32; 3], has: bool) {
let state = self.world.block(pos[0], pos[1], pos[2]);
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(mut s) = registry.state(state).cloned() else {
return;
};
+64 -7
View File
@@ -53,6 +53,19 @@ pub(super) struct LanHost {
pub broken: Vec<[f64; 3]>,
/// Hurt and death state of the mobs guests see.
mob_state: HashMap<u32, (i32, bool)>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
pub owner: Option<Owner>,
}
/// The player who owns an integrated server's world: a guest whose state is
/// the world's own player (`players/data/<singleplayer_uuid>.dat`), as in
/// single player.
pub(super) struct Owner {
pub uuid: u128,
/// The world's player as loaded, until the owner joins.
pub saved: Option<Box<horizon_client::save::Level>>,
}
/// A stable UUID for an entity that has none.
@@ -335,6 +348,14 @@ impl Game<'_> {
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
f64::from(g.saturation),
g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)),
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
@@ -430,7 +451,7 @@ impl Game<'_> {
encoder.tables = Some(
self.save
.tables
.get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets)))
.get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.pack.assets)))
.clone(),
);
let lan = Lan::start_with(sync.clone(), net)?;
@@ -454,6 +475,8 @@ impl Game<'_> {
play: HashMap::new(),
broken: Vec::new(),
mob_state: HashMap::new(),
mob_players: HashMap::new(),
owner: None,
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -466,7 +489,7 @@ impl Game<'_> {
return;
};
for g in &host.hub.guests {
playerdata::save(g, &self.world_root);
self.save_guest(&host, g);
}
host.hub.disconnect_all();
// Give the writer threads a moment to flush the disconnect packets.
@@ -483,6 +506,30 @@ impl Game<'_> {
}
}
/// Save a guest when they leave or the world closes: an integrated
/// server's owner with the world (`save_game`), anyone else in their file.
pub(super) fn save_guest(&mut self, host: &LanHost, guest: &horizon_client::lan::guest::Guest) {
if host.owner.as_ref().is_some_and(|o| o.uuid == guest.uuid) {
if guest.placed {
playerdata::store(guest, &mut self.level);
}
} else {
playerdata::save(guest, &self.world_root);
}
}
/// The integrated server's owner into the world's player, for `Level::write`.
pub(super) fn store_owner(&mut self) {
let Some(host) = &self.lan else {
return;
};
let Some(uuid) = host.owner.as_ref().map(|o| o.uuid) else {
return;
};
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) {
playerdata::store(g, &mut self.level);
}
}
/// The world's default game mode (`defaultgamemode`).
pub(super) fn set_default_game_mode(&mut self, mode: i32) {
self.level.game_mode = mode;
@@ -601,7 +648,7 @@ impl Game<'_> {
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: false,
difficulty_locked: self.level.difficulty_locked,
clock_rate: if self.ui.rules.bool("advance_time") {
self.ui.clock.rate
} else {
@@ -653,7 +700,7 @@ impl Game<'_> {
self.container_openers_changed(pos, false);
}
self.lan_crafting_left(&mut host, &mut guest);
playerdata::save(&guest, &self.world_root);
self.save_guest(&host, &guest);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
@@ -696,10 +743,20 @@ impl Game<'_> {
let default_mode = host.hub.config.default_game_mode;
let force = host.hub.config.force_game_mode;
let root = self.world_root.clone();
let owner = host.owner.as_mut();
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let known = playerdata::load(g, &root);
let saved = owner
.filter(|o| o.uuid == g.uuid)
.and_then(|o| o.saved.take());
let known = match saved {
Some(level) => {
playerdata::apply(g, &level);
level.position.is_some()
}
None => playerdata::load(g, &root),
};
if !known || force {
g.game_mode = default_mode;
}
@@ -716,7 +773,7 @@ impl Game<'_> {
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: false,
difficulty_locked: self.level.difficulty_locked,
clock_rate: self.ui.clock.rate,
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
@@ -875,7 +932,7 @@ impl Game<'_> {
let Some(host) = &self.lan else {
return;
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for m in host.models.values() {
let entity_start = out.len();
+138 -29
View File
@@ -11,8 +11,11 @@ use horizon_client::{
containers::BlockEntity,
entities::Experience,
items::ItemStack,
lan::{guest::SPECTATOR, menu::Rules},
motion::{MotionWorld, PlayerMotion},
lan::{
guest::SPECTATOR,
menu::{Rules, Slots},
},
motion::{MotionEvent, MotionWorld, PlayerMotion},
};
use horizon_core::geometry::Vec3;
use horizon_protocol::{
@@ -145,10 +148,22 @@ impl Game<'_> {
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
let host_station = self.station.take();
// The guest's own ender inventory; one the host has open goes back
// into the host's while the guest acts.
let host_ender = self.ender_open;
self.close_ender_chest();
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
self.lan_acting = Some(conn);
self.lan_acting_name = Some(g.name.clone());
self.lan_acting_uuid = Some(g.uuid);
let result = f(self);
self.lan_acting = None;
self.lan_acting_name = None;
self.lan_acting_uuid = None;
// An ender chest the guest opened: the menu shows their inventory
// itself (lan_open_container), not a stand-in block entity.
self.close_ender_chest();
// What the action opened: handed to the guest instead of the host.
let opened = self.container.take();
@@ -172,6 +187,13 @@ impl Game<'_> {
self.keys.remove(&KeyCode::ShiftLeft);
}
let g = &mut host.hub.guests[i];
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
if let Some(key) = host_ender {
self.world
.block_entities
.insert(key, BlockEntity::Chest(self.ender_items.clone()));
self.ender_open = Some(key);
}
let new_xp = std::mem::replace(&mut self.experience, xp);
g.xp_level = new_xp.level;
g.xp_progress = new_xp.progress;
@@ -240,30 +262,51 @@ impl Game<'_> {
/// Hand a container the guest opened over (ServerPlayer.openMenu);
/// false when it is not one a guest can open.
fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool {
let Some(entity) = self.world.block_entities.get(&pos) else {
return false;
};
let (menu, title) = match entity {
BlockEntity::Chest(items) => match items.len() {
27 => ("minecraft:generic_9x3", "container.chest"),
9 => ("minecraft:generic_3x3", "container.dispenser"),
5 => ("minecraft:hopper", "container.hopper"),
_ => return false,
},
_ => return false,
};
let name = &self
.res
.facts
.get(self.world.block(pos.0, pos.1, pos.2))
.name;
let title = match &**name {
"minecraft:barrel" => "container.barrel",
"minecraft:dropper" => "container.dropper",
n if n.ends_with("shulker_box") => "container.shulkerBox",
_ => title,
let (menu, title, slots) = if &**name == "minecraft:ender_chest" {
// EnderChestBlock.useWithoutItem: the player's own inventory.
(
"minecraft:generic_9x3",
"container.enderchest",
Slots::Ender,
)
} else if let Some((other, right)) = self.chest_partner(pos) {
// ChestBlock.combine: the right half's slots come first.
let halves = if right {
Slots::Double(pos, other)
} else {
Slots::Double(other, pos)
};
("minecraft:generic_9x6", "container.chestDouble", halves)
} else {
let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&pos) else {
return false;
};
let (menu, title) = match items.len() {
27 => ("minecraft:generic_9x3", "container.chest"),
9 => ("minecraft:generic_3x3", "container.dispenser"),
5 => ("minecraft:hopper", "container.hopper"),
_ => return false,
};
let title = match &**name {
"minecraft:barrel" => "container.barrel",
"minecraft:dropper" => "container.dropper",
n if n.ends_with("shulker_box") => "container.shulkerBox",
_ => title,
};
(menu, title, Slots::Block(pos))
};
let Some(items) = host
.hub
.guest(conn)
.and_then(|g| slots.read(&self.world, g))
else {
return false;
};
let items = entity.slots().to_vec();
// ServerPlayer.openMenu closes the menu that was open.
self.guest_container_closed(host, conn);
host.hub.open_container(
@@ -271,6 +314,7 @@ impl Game<'_> {
menu,
horizon_protocol::text::translatable(title, &[]),
pos,
slots,
items,
);
true
@@ -401,8 +445,13 @@ impl Game<'_> {
if spectator {
return;
}
// handleUseItem: the client's rotation, then the item alone. What it
// looked at a moment ago (a block, a mob) is UseItemOn's or Interact's.
self.as_guest(host, conn, |g| {
(g.yaw, g.pitch) = (p.yaw, p.pitch);
g.lan_item_only = true;
let _ = g.use_item();
g.lan_item_only = false;
});
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
@@ -582,6 +631,12 @@ impl Game<'_> {
if host.hub.guests[gi].spectator() {
return;
}
if let Some(victim) = Self::pvp_victim(host, conn, id) {
if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) {
self.pvp_land(host, victim, &strike);
}
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
if self.look_at_entity(host, gi, id).is_none() {
return;
@@ -589,6 +644,10 @@ impl Game<'_> {
self.as_guest(host, conn, |g| {
g.attack();
});
// The mob now answers to this guest (game/lan_mobs.rs).
if let Ok(id) = u32::try_from(id) {
host.mob_players.insert(id, conn);
}
host.hub.guests[gi].yaw = old_yaw;
host.hub.guests[gi].pitch = old_pitch;
}
@@ -766,48 +825,98 @@ impl Game<'_> {
}
/// The guest's body on the server each tick: ServerPlayer.tick's damage
/// clock and Entity.baseTick's fluid phase, then
/// ServerPlayer.doCheckFallDamage for each move the guest made (the fall
/// distance grows while they go down and hurts them where they land, as
/// the host's own landing does; water resets it, lava halves it), then
/// regeneration and the food tick (ServerPlayer.doTick).
/// clock and Entity.baseTick's fluid phase (burning), then for each move
/// the guest made ServerGamePacketListenerImpl.handleMovePlayer's jump
/// (`ServerPlayer.jumpFromGround`'s exhaustion),
/// ServerPlayer.doCheckFallDamage (the fall distance grows while they go
/// down and hurts them where they land, as the host's own landing does;
/// water resets it, lava halves it) and checkMovementStatistics (the
/// exhaustion of sprinting and swimming), then LivingEntity.baseTick's
/// hazards (drowning, lava, fire blocks, suffocation, the void), and
/// regeneration and the food tick (ServerPlayer.doTick). Their hurt
/// sounds are heard at the guest.
fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) {
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let moves = std::mem::take(&mut g.moves);
let from_ground = if moves.is_empty() {
g.on_ground
} else {
g.moves_from_ground
};
if g.spectator() {
return;
}
self.as_guest(host, conn, |game| {
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sounds = self.as_guest(host, conn, |game| {
let (rules, health) = (game.world.health_rules, &game.motion.health);
let Some(player) = game.player.as_mut() else {
return;
return Vec::new();
};
let mut w = MotionWorld {
entities: &[],
player,
scene: &mut game.world,
assets: &game.res.assets,
assets: &game.pack.assets,
collision_binding: game.collision,
resources: game.motion,
};
w.player.health.advance_clock();
let _ = w.fluid_base_tick();
w.player.ground.on_ground = from_ground;
for (moved, on_ground) in moves {
let movement = Vec3::new(moved[0], moved[1], moved[2]);
if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 {
let sprinting = w.player.sprinting;
w.player
.health
.food
.add_exhaustion(if sprinting { 0.2 } else { 0.05 });
}
let landed = (|| -> horizon_client::Result<()> {
w.set_on_ground_with_movement(on_ground, false, movement)?;
let pos = w.legacy_on_position()?;
let state = w.block_state(pos)?;
w.check_fall_damage(moved[1], on_ground, state, pos)
w.check_fall_damage(moved[1], on_ground, state, pos)?;
w.check_movement_statistics(movement)
})();
if landed.is_err() {
break;
}
}
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
let _ = w.player.peaceful_regeneration(rules);
let _ = w.player.food_tick(health, rules);
std::mem::take(&mut w.player.events)
.into_iter()
.filter_map(|e| match e {
MotionEvent::HurtSound(sound) => Some(sound),
_ => None,
})
.collect::<Vec<_>>()
});
for sound in sounds.into_iter().flatten() {
self.player_hurt_sound(sound, at);
}
}
/// `Player.isInWall`: a suffocating block in the 0.48-wide box at the
/// eyes. Suffocating is a full collision box that is also a full render
/// cube (`BlockBehaviour.isSuffocating`'s default; glass and the like
/// opt out), as the mobs' check has it.
fn in_wall(&self, at: [f64; 3], eye_height: f64) -> bool {
let (y, half) = ((at[1] + eye_height).floor() as i32, 0.24);
let range = |v: f64| (v - half).floor() as i32..=(v + half).floor() as i32;
range(at[0]).any(|x| {
range(at[2]).any(|z| {
let f = self.res.facts.get(self.world.block(x, y, z));
f.full_collision && f.solid_render
})
})
}
/// The crack animation other players see.
+305
View File
@@ -0,0 +1,305 @@
//! Mobs and the guests of an open world. The mob code sees one player
//! (`MobWorld.player`, `Who::Player`); with guests on, each mob sees the
//! player vanilla's `Level.getNearestPlayer` would give it, and keeps the
//! guest it targets until it lets go. What it then does to `Who::Player`
//! (hits, pushes, fire, its projectiles) runs with that guest swapped in.
use super::{Game, lan::LanHost};
use horizon_client::{
mobs::{Mob, MobEvent, PlayerView, Who},
projectiles::{Hit, Projectile},
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// The guests mobs can see this tick, by connection.
pub(super) type GuestViews = Vec<(u32, PlayerView)>;
/// The player a mob sees this tick: `None` for the host, else a guest.
/// A mob that targets a guest, or that a guest hurt in the last 100 ticks
/// (`LivingEntity.getLastHurtByMob`), keeps them while they are still a
/// valid target; otherwise it sees the nearest player
/// (`TargetingConditions`: alive, neither creative nor spectator), or the
/// nearest one that is not a spectator if none qualifies.
pub(super) fn player_for(
m: &Mob,
host: Option<&PlayerView>,
guests: &GuestViews,
bound: Option<u32>,
) -> Option<u32> {
let targeting = m.ai.target == Some(Who::Player)
|| m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100;
choose(m.position, targeting, host, guests, bound)
}
fn choose(
at: Vec3,
targeting: bool,
host: Option<&PlayerView>,
guests: &GuestViews,
bound: Option<u32>,
) -> Option<u32> {
let targetable = |v: &PlayerView| v.alive && !v.creative && !v.spectator;
if targeting
&& let Some(conn) = bound
&& guests.iter().any(|(c, v)| *c == conn && targetable(v))
{
return Some(conn);
}
let d = |v: &PlayerView| at.distance_squared(v.position);
let nearest = |ok: &dyn Fn(&PlayerView) -> bool| {
let mut best = host.filter(|v| ok(v)).map(|v| (None, d(v)));
for (conn, v) in guests.iter().filter(|(_, v)| ok(v)) {
if best.is_none_or(|(_, b)| d(v) < b) {
best = Some((Some(*conn), d(v)));
}
}
best
};
nearest(&targetable)
.or_else(|| nearest(&|v: &PlayerView| v.alive && !v.spectator))
.and_then(|(conn, _)| conn)
}
/// The events of a mob's tick that act on the player it sees.
pub(super) fn acts_on_player(e: &MobEvent) -> bool {
matches!(
e,
MobEvent::AttackPlayer(..)
| MobEvent::DamagePlayer { .. }
| MobEvent::Push {
target: Who::Player,
..
}
| MobEvent::Ignite {
target: Who::Player,
..
}
| MobEvent::Launch {
target: Who::Player,
..
}
)
}
impl Game<'_> {
/// How mobs see each guest in play (`player_view` with the guest swapped
/// in; what the host alone tracks, such as its last attacker, stays out).
pub(super) fn lan_guest_views(&mut self) -> GuestViews {
let Some(mut host) = self.lan.take() else {
return Vec::new();
};
let conns: Vec<(u32, u128, [f64; 3])> = host
.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead)
.map(|g| {
let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]);
(g.conn, g.uuid, moved)
})
.collect();
let mut views = Vec::new();
for (conn, uuid, moved) in conns {
if let Some(Some(mut v)) = self.as_guest(&mut host, conn, |g| g.player_view()) {
v.hurt_by = None;
v.last_hurt = None;
v.hero = false;
v.velocity = Vec3::new(moved[0], moved[1], moved[2]);
v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid);
v.allies = Default::default();
views.push((conn, v));
}
}
self.lan = Some(host);
views
}
/// Mob events aimed at a guest, run as that guest (`guest_hit_by`).
pub(super) fn lan_guest_mob_events(&mut self, events: Vec<(u32, MobEvent)>) {
if events.is_empty() {
return;
}
let Some(mut host) = self.lan.take() else {
return;
};
for (conn, e) in events {
self.guest_hit_by(&mut host, conn, |g| {
let _ = g.handle_mob_events(vec![e]);
});
}
self.lan = Some(host);
}
/// The guests a projectile can hit, under their entity ids.
pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> {
let Some(host) = self.lan.as_ref() else {
return Vec::new();
};
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g)))
.collect()
}
/// A projectile that hit a guest: its hit runs as theirs. False when
/// `id` is not a guest.
pub(super) fn lan_projectile_hit(&mut self, p: &Projectile, id: u32, at: Vec3) -> bool {
let Some(mut host) = self.lan.take() else {
return false;
};
let conn = host
.hub
.guests
.iter()
.find(|g| g.entity_id as u32 == id)
.map(|g| g.conn);
if let Some(conn) = conn {
self.guest_hit_by(&mut host, conn, |g| {
let hit = Hit::Entity {
who: Who::Player,
at,
};
let _ = g.projectile_hit(p, hit);
});
}
self.lan = Some(host);
conn.is_some()
}
}
impl Game<'_> {
/// Hurt a guest: `f` runs as them, and the knockback it gave reaches
/// their client (`hurtMarked`: ClientboundSetEntityMotionPacket).
pub(super) fn guest_hit_by<R>(
&mut self,
host: &mut LanHost,
conn: u32,
f: impl FnOnce(&mut Self) -> R,
) -> Option<R> {
let (result, pushed) = self.as_guest(host, conn, |g| {
let before = g.player.as_ref().map(|p| p.velocity);
let result = f(g);
let after = g.player.as_ref().map(|p| p.velocity);
(result, after.filter(|v| Some(*v) != before))
})?;
if let (Some(v), Some(g)) = (pushed, host.hub.guest(conn)) {
g.send(&C::SetEntityMotion(play::SetEntityMotion {
id: g.entity_id,
velocity: [v.x, v.y, v.z],
}));
}
Some(result)
}
}
/// A guest as the blocks that look for players see them
/// (`PlayerDetector`, `level.getPlayers`: the dead ones too).
pub(super) struct Present {
pub uuid: [i32; 4],
pub position: [f64; 3],
pub eye: [f64; 3],
pub height: f32,
pub creative: bool,
pub spectator: bool,
pub alive: bool,
}
impl Game<'_> {
/// Every guest in the world (`ServerLevel.getPlayers` past the host).
pub(super) fn lan_present(&self) -> Vec<Present> {
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
guests
.filter(|g| g.placed && g.loaded)
.map(|g| {
let [x, y, z] = g.position;
Present {
uuid: horizon_client::lan::playerdata::uuid_ints(g.uuid),
position: g.position,
eye: [x, y + g.eye_height(), z],
height: if g.sneaking { 1.5 } else { 1.8 },
creative: g.creative(),
spectator: g.spectator(),
alive: !g.dead,
}
})
.collect()
}
/// The UUID of the player acting: the guest `as_guest` runs, else the host.
pub(super) fn acting_uuid(&self) -> [i32; 4] {
self.lan_acting_uuid
.map(horizon_client::lan::playerdata::uuid_ints)
.or(self.level.player_uuid)
.unwrap_or_default()
}
}
/// A guest's bounding box (0.6 wide, 1.8 tall, 1.5 crouching).
pub(super) fn guest_bounds(g: &horizon_client::lan::guest::Guest) -> Aabb {
let [x, y, z] = g.position;
let height = if g.sneaking { 1.5 } else { 1.8 };
Aabb::new(
Vec3::new(x - 0.3, y, z - 0.3),
Vec3::new(x + 0.3, y + height, z + 0.3),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn view(x: f64, creative: bool) -> PlayerView {
PlayerView {
position: Vec3::new(x, 64.0, 0.0),
bounds: Aabb::new(Vec3::new(x, 64.0, 0.0), Vec3::new(x, 65.8, 0.0)),
eye: [x, 65.62, 0.0],
alive: true,
creative,
sneaking: false,
look: [0.0; 3],
main_hand: None,
off_hand: None,
head: None,
armor_cover: 0.0,
spectator: false,
gold_armor: false,
hurt_by: None,
last_hurt: None,
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
uuid: [0; 4],
allies: Default::default(),
}
}
const MOB: Vec3 = Vec3::new(0.0, 64.0, 0.0);
#[test]
fn the_nearest_survival_player_is_seen() {
let host = view(10.0, false);
let guests = vec![(7, view(3.0, false)), (8, view(-5.0, false))];
assert_eq!(choose(MOB, false, Some(&host), &guests, None), Some(7));
// A creative guest is passed over for the host further away.
let guests = vec![(7, view(3.0, true))];
assert_eq!(choose(MOB, false, Some(&host), &guests, None), None);
// Nobody targetable: the nearest one is still seen.
let host = view(10.0, true);
assert_eq!(choose(MOB, false, Some(&host), &guests, None), Some(7));
assert_eq!(choose(MOB, false, None, &Vec::new(), None), None);
}
#[test]
fn a_targeted_guest_stays_the_target() {
let host = view(1.0, false);
let guests = vec![(7, view(12.0, false))];
assert_eq!(choose(MOB, true, Some(&host), &guests, Some(7)), Some(7));
// Gone creative: the mob looks again.
let guests = vec![(7, view(12.0, true))];
assert_eq!(choose(MOB, true, Some(&host), &guests, Some(7)), None);
// Without a target the nearest player wins.
let guests = vec![(7, view(12.0, false))];
assert_eq!(choose(MOB, false, Some(&host), &guests, Some(7)), None);
}
}
+110
View File
@@ -0,0 +1,110 @@
//! Players hitting players in an open world (`Player.attack` on a player):
//! the host hits a guest, a guest hits the host or another guest. The hit
//! is worked out as the attacker (weapon, attack strength, critical hit,
//! enchantments, a mace's smash) and lands on the victim like any player
//! attack (blocking, armour, knockback), when the `pvp` game rule allows it
//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`).
use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector};
/// Who a player's attack lands on.
#[derive(Clone, Copy)]
pub(super) enum Victim {
Host,
Guest(u32),
}
/// The attacker's side of the hit.
pub(super) struct Strike {
amount: f32,
scale: f32,
crit: bool,
from: [f64; 3],
}
impl Game<'_> {
/// The guest on the host's crosshair and how far, within reach.
pub(super) fn guest_hit(&self) -> Option<(u32, f64)> {
let host = self.lan.as_ref()?;
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let reach = if self.creative { 5.0 } else { 3.0 };
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?)))
.min_by(|a, b| a.1.total_cmp(&b.1))
}
/// The host's attack on the guest under the crosshair, when no mob or
/// block is nearer.
pub(super) fn attack_guest(&mut self) -> bool {
let Some((conn, d)) = self.guest_hit() else {
return false;
};
if self.mob_hit().is_some_and(|(_, m)| m < d) || !self.before_block(d) {
return false;
}
let Some(mut host) = self.lan.take() else {
return false;
};
if let Some(strike) = self.pvp_strike() {
self.pvp_land(&mut host, Victim::Guest(conn), &strike);
}
self.lan = Some(host);
true
}
/// The player `id` that guest `conn` attacks, if it is one.
pub(super) fn pvp_victim(host: &LanHost, conn: u32, id: i32) -> Option<Victim> {
if id == host.host_entity {
return Some(Victim::Host);
}
host.hub
.guests
.iter()
.find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead)
.map(|g| Victim::Guest(g.conn))
}
/// The attacker's side of `Player.attack` (the host, or a guest swapped
/// in): the damage, the charge reset, the exhaustion and the swing.
pub(super) fn pvp_strike(&mut self) -> Option<Strike> {
let p = self.player.as_ref()?;
let from = [p.position.x, p.position.y, p.position.z];
let (amount, scale, crit) = self.melee_damage("minecraft:player");
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
{
p.health.food.exhaustion = (p.health.food.exhaustion + 0.1).min(40.0);
}
self.swing_arm();
Some(Strike {
amount,
scale,
crit,
from,
})
}
/// The hit landing on the victim, then the attacker's attack sound.
pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) {
let hurt = self.ui.rules.bool("pvp")
&& match victim {
Victim::Host => self.mob_hits_player(s.amount, s.from, "minecraft:player_attack"),
Victim::Guest(conn) => self
.guest_hit_by(host, conn, |g| {
g.mob_hits_player(s.amount, s.from, "minecraft:player_attack")
})
.unwrap_or(false),
};
let sound = match (hurt, s.crit, s.scale > 0.9) {
(false, ..) => "minecraft:entity.player.attack.nodamage",
(true, true, _) => "minecraft:entity.player.attack.crit",
(true, false, true) => "minecraft:entity.player.attack.strong",
(true, false, false) => "minecraft:entity.player.attack.weak",
};
self.audio.play(sound, Some(s.from), 1.0, 1.0);
}
}
+740 -96
View File
@@ -2,11 +2,17 @@
//! that opens the world to the local network (the 26.3 replacement of the
//! old "Open to LAN" screen): default and personal game mode, cheats,
//! difficulty, LAN on/off with its port, command access for guests and
//! forcing the game mode.
use super::{Game, Screen, lan::LanSettings};
//! forcing the game mode. Its difficulty lock asks first (PopupScreen), and
//! Restrictions opens RestrictionsScreen.
use super::{
Game, Screen,
game_rules_screen::{Exit, RulesScreen},
lan::LanSettings,
};
use horizon_client::{
font::Font,
hud::{HudBatch, rgba},
text::Text,
text::{Text, named_color},
ui::{self, EditBox},
};
use winit::{event::KeyEvent, keyboard::PhysicalKey};
@@ -22,7 +28,27 @@ pub(super) struct WorldOptions {
hint: u16,
guest_commands: bool,
force: bool,
hardcore: bool,
/// The level's own lock (LevelData.isDifficultyLocked).
difficulty_locked: bool,
/// wantedDifficultyLocked: the lock icon, from the lock or hardcore.
locked: bool,
initial: Snapshot,
/// ScrollableLayout's scroll amount.
scroll: f32,
view: View,
/// InWorldGameRulesScreen, while it is open.
rules: Option<RulesScreen>,
}
/// The screen on show: the options, the lock's question over them, or the
/// RestrictionsScreen or InWorldGameRulesScreen they opened (all return to
/// the same options).
#[derive(Clone, Copy, Debug, PartialEq)]
enum View {
Options,
LockQuestion,
Restrictions,
GameRules,
}
#[derive(Clone, PartialEq)]
struct Snapshot {
@@ -30,6 +56,7 @@ struct Snapshot {
personal_mode: i32,
cheats: bool,
difficulty: u8,
locked: bool,
lan: bool,
port: u16,
guest_commands: bool,
@@ -39,12 +66,33 @@ struct Snapshot {
const MODES: [&str; 4] = ["survival", "creative", "adventure", "spectator"];
const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
#[derive(Clone, Copy, PartialEq)]
/// HeaderAndFooterLayout's header and footer heights.
const HEADER: f32 = 33.0;
const FOOTER: f32 = 33.0;
/// The scrolled content: both grids, each padded by 8 and 8 apart.
const CONTENT: f32 = 218.0;
/// The category headings' tops (FocusableTextWidget, padding 4).
const GENERAL_TOP: f32 = 8.0;
const MULTIPLAYER_TOP: f32 = 145.0;
/// The port box's top beside the LAN button.
const PORT_TOP: f32 = 166.0;
/// PopupScreen: 250 wide less its 18 pixel border each side, two buttons
/// `min((214 - 6) / 2, 150)` wide and 6 apart, rows 12 apart.
const POPUP_CONTENT: f32 = 214.0;
const POPUP_BUTTON: f32 = 104.0;
/// RestrictionsScreen's text widgets: 250 wide, padded by 4.
const RESTRICTION_WIDTH: f32 = 250.0;
#[derive(Clone, Copy, Debug, PartialEq)]
enum Button {
DefaultMode,
PersonalMode,
Cheats,
Difficulty,
/// DifficultyButtons.lockButton (LockIconButton).
Lock,
GameRules,
Restrictions,
Lan,
CommandAccess,
Force,
@@ -72,6 +120,7 @@ impl WorldOptions {
personal_mode: self.personal_mode,
cheats: self.cheats,
difficulty: self.difficulty,
locked: self.locked,
lan: self.lan,
port: if self.lan {
self.parsed_port().unwrap_or(0)
@@ -86,26 +135,56 @@ impl WorldOptions {
let valid = !self.lan || self.parsed_port().is_some();
valid && self.snapshot() != self.initial
}
fn buttons(w: f32) -> Vec<(Button, f32, f32, f32)> {
let x = (w / 2.0 - 154.0).floor();
/// The scrolled content's top: under the header, less the scroll.
fn top(&self) -> f32 {
HEADER - self.scroll.trunc()
}
/// The grids' left edge: the content (308 wide, padded by 8) centred
/// in a ScrollableLayout reserving 10 pixels for the scrollbar each side.
fn left(w: f32) -> f32 {
(w / 2.0).floor() - 154.0
}
/// The scrolled widgets: each grid's rows 4 apart, columns 8 apart.
fn buttons(w: f32, top: f32) -> Vec<(Button, f32, f32, f32)> {
let x = Self::left(w);
let right = x + 158.0;
vec![
(Button::DefaultMode, x, 38.0, 308.0),
(Button::PersonalMode, x, 62.0, 308.0),
(Button::Cheats, x, 86.0, 150.0),
(Button::Difficulty, right, 86.0, 150.0),
(Button::Lan, x, 126.0, 150.0),
(Button::CommandAccess, x, 150.0, 150.0),
(Button::Force, right, 150.0, 150.0),
(Button::DefaultMode, x, top + 29.0, 308.0),
(Button::PersonalMode, x, top + 53.0, 308.0),
(Button::Cheats, x, top + 77.0, 150.0),
// DifficultyButtons: the cycle button gives the lock its 20 pixels.
(Button::Difficulty, right, top + 77.0, 130.0),
(Button::Lock, right + 130.0, top + 77.0, 20.0),
(Button::GameRules, x, top + 101.0, 150.0),
(Button::Restrictions, right, top + 101.0, 150.0),
(Button::Lan, x, top + 166.0, 150.0),
(Button::CommandAccess, x, top + 190.0, 150.0),
(Button::Force, right, top + 190.0, 150.0),
]
}
/// The footer's two buttons, centred in its 33 pixels (FrameLayout
/// truncates the 6.5 pixel offset).
fn footer(w: f32, h: f32) -> [(Button, f32, f32, f32); 2] {
let x = (w / 2.0 - 154.0).floor();
let x = Self::left(w);
[
(Button::Apply, x, h - 28.0, 150.0),
(Button::Cancel, x + 158.0, h - 28.0, 150.0),
(Button::Apply, x, h - FOOTER + 6.0, 150.0),
(Button::Cancel, x + 158.0, h - FOOTER + 6.0, 150.0),
]
}
/// The widgets under the pointer's row: scrolled ones only inside the
/// scroll area.
fn hit(&self, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option<Button> {
let inside = y >= HEADER && y < h - FOOTER;
Self::buttons(w, self.top())
.into_iter()
.filter(|_| inside)
.chain(Self::footer(w, h))
.find(|(b, bx, by, bw)| self.active(*b) && ui::hovered((x, y), *bx, *by, *bw, 20.0))
.map(|b| b.0)
}
fn max_scroll(h: f32) -> f32 {
(CONTENT - (h - HEADER - FOOTER)).max(0.0)
}
fn label(&self, b: Button) -> Text {
let mode = |m: i32| {
Text::translate(
@@ -122,6 +201,9 @@ impl WorldOptions {
mode(self.personal_mode),
),
Button::Cheats => labelled("selectWorld.allowCommands", on_off(self.cheats)),
Button::Lock => Text::translate("narrator.button.difficulty_lock", &[]),
Button::GameRules => Text::translate("editGamerule.inGame.button", &[]),
Button::Restrictions => Text::translate("restrictions_screen.button", &[]),
Button::Difficulty => labelled(
"options.difficulty",
Text::translate(
@@ -139,22 +221,188 @@ impl WorldOptions {
),
Button::Force => labelled(
"options.worldOptions.guest.force_game_mode",
on_off(self.force || !self.lan),
on_off(self.force || !self.lan || self.hardcore),
),
Button::Apply => Text::translate("menu.multiplayerOptions.applyChanges", &[]),
Button::Cancel => Text::translate("gui.cancel", &[]),
}
}
/// WorldOptionsScreen.updateButton and the update*Button methods.
fn active(&self, b: Button) -> bool {
match b {
Button::DefaultMode | Button::PersonalMode => self.cheats && !self.hardcore,
// An owner's commands come with Allow Commands.
Button::Cheats => !self.hardcore || self.initial.cheats,
// DifficultyButtons.updateDifficultyButtonsState: the level's
// lock or hardcore, not the wanted lock.
Button::Difficulty | Button::Lock => !self.hardcore && !self.difficulty_locked,
// updateButton from the player's permission: the Allow Commands
// switch leaves it (updatePermissionDependentButtons(.., false)).
Button::GameRules => !self.hardcore && self.initial.cheats,
Button::Restrictions => true,
Button::CommandAccess => self.lan && self.cheats,
Button::Force => self.lan && !(self.guest_commands && self.cheats),
Button::Force => self.lan && !(self.guest_commands && self.cheats) && !self.hardcore,
Button::Apply => self.changed(),
_ => true,
Button::Lan | Button::Cancel => true,
}
}
}
/// MultiLineLabel: the lines of `t` wrapped to `width`.
fn wrap(font: &Font, t: &Text, width: f32) -> Vec<Text> {
font.split_lines(t, width)
.into_iter()
.map(|(line, _)| line)
.collect()
}
fn widest(font: &Font, lines: &[Text]) -> f32 {
lines.iter().map(|l| font.width_text(l)).fold(0.0, f32::max)
}
/// Centred MultiLineTextWidget lines: each centred on `mid` from `top`, 9 apart.
fn centred_lines(font: &Font, lines: Vec<Text>, mid: f32, top: f32) -> Vec<(Text, f32, f32)> {
lines
.into_iter()
.enumerate()
.map(|(i, line)| {
let x = mid - (font.width_text(&line) / 2.0).trunc();
(line, x, top + 9.0 * i as f32)
})
.collect()
}
/// PopupScreen centred on the screen: its title (bold) and message lines,
/// the background sprite's rectangle and its two buttons.
struct Popup {
lines: Vec<(Text, f32, f32)>,
frame: (f32, f32, f32, f32),
buttons: [(f32, f32); 2],
}
impl Popup {
fn new(font: &Font, title: &Text, message: &Text, (w, h): (f32, f32)) -> Self {
let blocks = [
wrap(font, title, POPUP_CONTENT),
wrap(font, message, POPUP_CONTENT),
];
let row = 2.0 * POPUP_BUTTON + 6.0;
let lw = blocks.iter().map(|b| widest(font, b)).fold(row, f32::max);
let lh = blocks
.iter()
.map(|b| 9.0 * b.len() as f32 + 12.0)
.sum::<f32>()
+ 20.0;
let (x, y) = (((w - lw) / 2.0).trunc(), ((h - lh) / 2.0).trunc());
let mut lines = Vec::new();
let mut top = y;
for block in blocks {
let bw = widest(font, &block);
let mid = x + ((lw - bw) / 2.0).trunc() + (bw / 2.0).trunc();
let n = block.len() as f32;
lines.extend(centred_lines(font, block, mid, top));
top += 9.0 * n + 12.0;
}
let bx = x + ((lw - row) / 2.0).trunc();
Self {
lines,
frame: (x - 18.0, y - 18.0, lw + 36.0, lh + 36.0),
buttons: [(bx, top), (bx + POPUP_BUTTON + 6.0, top)],
}
}
/// The lock's question: WorldOptionsScreen's Apply when the lock changed.
fn lock_question(font: &Font, difficulty: u8, size: (f32, f32)) -> Self {
let name = Text::translate(
&format!(
"options.difficulty.{}",
DIFFICULTIES[usize::from(difficulty) & 3]
),
&[],
);
Self::new(
font,
&Text::translate("difficulty.lock.title", &[]).bold(),
&Text::translate("difficulty.lock.question", &[name]),
size,
)
}
}
/// RestrictionsScreen for the player of a single-player world, whose chat
/// abilities come from the Chat option alone (Minecraft.computeChatAbilities).
struct Restrictions {
lines: Vec<(Text, f32, f32)>,
/// The restriction's action, 200 wide: Chat Settings.
action: Option<(f32, f32)>,
/// The ScrollableLayout's top and bottom.
area: (f32, f32),
}
impl Restrictions {
fn new(font: &Font, chat_visibility: u8, (w, h): (f32, f32)) -> Self {
let red = named_color("red").unwrap_or(0xFF5555);
let green = named_color("green").unwrap_or(0x55FF55);
let inner = RESTRICTION_WIDTH - 8.0;
// ChatVisiblity HIDDEN takes chat and commands, SYSTEM the chat.
let restriction = match chat_visibility {
2 => Some("chat_restriction.chat_and_commands_disabled_by_options"),
1 => Some("chat_restriction.chat_disabled_by_options"),
_ => None,
};
let (chat, commands) = (chat_visibility == 0, chat_visibility < 2);
// The body's widgets: text blocks (lines, top) and the action's top.
let mut blocks = Vec::new();
let mut action = None;
let mut y = 0.0;
if let Some(key) = restriction {
let lines = wrap(
font,
&Text::translate(key, &[]).bold().with_color(red),
inner,
);
let n = lines.len() as f32;
blocks.push((lines, y));
y += 9.0 * n + 8.0;
action = Some(y);
// The button, then a 10 pixel SpacerElement.
y += 20.0 + 10.0;
}
let permissions = [
("send_messages", chat),
("send_commands", commands),
("receive_system_messages", commands),
("receive_player_messages", chat),
];
let lines: Vec<Text> = permissions
.iter()
.flat_map(|&(id, allowed)| {
let state = if allowed { "allowed" } else { "denied" };
let t =
Text::translate(&format!("restrictions_screen.permission.{id}.{state}"), &[])
.with_color(if allowed { green } else { red });
wrap(font, &t, inner)
})
.collect();
let n = lines.len() as f32;
blocks.push((lines, y));
y += 9.0 * n + 8.0;
// HeaderAndFooterLayout: 30 under the header if it fits; the
// ScrollableLayout keeps 10 pixels each side for its scrollbar.
let height = y.min(h - HEADER - FOOTER);
let top = (HEADER + 30.0).min(h - FOOTER - height);
let x = ((w - (RESTRICTION_WIDTH + 20.0)) / 2.0).trunc() + 10.0;
let mid = x + RESTRICTION_WIDTH / 2.0;
Self {
lines: blocks
.into_iter()
.flat_map(|(lines, by)| centred_lines(font, lines, mid, top + by + 4.0))
.collect(),
action: action.map(|ay| (x + 25.0, top + ay)),
area: (top, top + height),
}
}
/// The footer's Done, 200 wide.
fn done(w: f32, h: f32) -> (f32, f32) {
(((w - 200.0) / 2.0).trunc(), h - FOOTER + 6.0)
}
}
impl Game<'_> {
pub(super) fn open_world_options(&mut self) {
let hint = horizon_client::lan::available_port();
@@ -177,11 +425,18 @@ impl Game<'_> {
hint,
guest_commands,
force,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
locked: self.level.difficulty_locked || self.level.hardcore,
scroll: 0.0,
view: View::Options,
rules: None,
initial: Snapshot {
default_mode: 0,
personal_mode: 0,
cheats: false,
difficulty: 0,
locked: false,
lan: false,
port: 0,
guest_commands: false,
@@ -198,98 +453,340 @@ impl Game<'_> {
self.screen = Screen::Paused;
}
/// Escape: the question and RestrictionsScreen return to the options
/// (their onClose), which close; the game rules ask first.
pub(super) fn world_options_escape(&mut self) {
match self.world_options.as_mut() {
Some(o) if o.view == View::GameRules => {
if let Some(exit) = o.rules.as_mut().and_then(RulesScreen::escape) {
self.close_game_rules(exit);
}
}
Some(o) if o.view != View::Options => o.view = View::Options,
_ => self.close_world_options(),
}
}
/// InWorldGameRulesScreen's exit, back to the options. Done sends the
/// changed rules (ServerboundSetGameRulePacket), which the server's
/// handleSetGameRule sets for a gamemaster and tells its operators.
fn close_game_rules(&mut self, exit: Exit) {
if let Some(o) = self.world_options.as_mut() {
o.view = View::Options;
o.rules = None;
}
let Exit::Apply(changes) = exit else {
return;
};
if !self.allow_commands() || changes.is_empty() {
return;
}
for (name, value) in changes {
self.ui.rules.set(name, value);
self.system_message(Text::tr("commands.gamerule.set", &[&name, &value]));
}
self.sync_rules();
}
pub(super) fn draw_world_options(&mut self, batch: &mut HudBatch) {
let Some(mut o) = self.world_options.take() else {
return;
};
let atlas = &self.res.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let centered = |batch: &mut HudBatch, key: &str, y: f32| {
let t = Text::translate(key, &[]);
let tw = atlas.font.width_text(&t);
batch.text_styled(atlas, &t, ((w - tw) / 2.0).floor(), y, u32::MAX, true);
};
centered(batch, "options.worldOptions.title", 12.0);
centered(batch, "options.worldOptions.general.title", 26.0);
centered(batch, "options.worldOptions.multiplayer.title", 114.0);
for (b, x, y, bw) in WorldOptions::buttons(w)
.into_iter()
.chain(WorldOptions::footer(w, h))
{
let active = o.active(b);
let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0);
ui::button(batch, atlas, x, y, bw, 20.0, &o.label(b), active, hover);
match o.view {
View::Options => self.draw_options_view(&mut o, batch, self.cursor),
View::LockQuestion => {
// PopupScreen: the screen behind without the pointer, then the popup.
self.draw_options_view(&mut o, batch, (-1.0, -1.0));
self.draw_lock_question(&o, batch);
}
View::Restrictions => self.draw_restrictions(batch),
View::GameRules => {
if let Some(rules) = o.rules.as_mut() {
rules.draw(batch, &self.atlas, self.cursor);
}
}
}
// The port box sits beside the LAN button.
let x = (w / 2.0 - 154.0).floor() + 158.0;
o.port.x = x;
o.port.y = 126.0;
o.port.focused = o.lan && o.port.focused;
if o.lan {
o.port.draw(batch, atlas, None);
if o.port.value.is_empty() {
let hint = Text::literal(o.hint.to_string());
batch.text_styled(
atlas,
&hint,
x + 4.0,
132.0,
rgba(160, 160, 160, 255),
false,
);
}
if o.parsed_port().is_none() {
let t = Text::translate(
"lanServer.port.invalid",
&[Text::literal("1024"), Text::literal("65535")],
);
let first = t.clone();
batch.text_styled(atlas, &first, x, 148.0, rgba(255, 85, 85, 255), true);
}
} else {
self.world_options = Some(o);
}
fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) {
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
// Screen.extractTransparentBackground.
batch.fill_gradient(
atlas,
(0.0, 0.0, w, h),
rgba(0x10, 0x10, 0x10, 0xC0),
rgba(0x10, 0x10, 0x10, 0xD0),
);
let p = Popup::lock_question(&atlas.font, o.difficulty, (w, h));
let (fx, fy, fw, fh) = p.frame;
ui::nine_slice(
batch,
atlas,
"gui/sprites/popup/background",
fx,
fy,
fw,
fh,
u32::MAX,
);
for (line, x, y) in &p.lines {
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
}
for ((bx, by), key) in p.buttons.into_iter().zip(["gui.yes", "gui.no"]) {
let hover = ui::hovered(self.cursor, bx, by, POPUP_BUTTON, 20.0);
let label = Text::translate(key, &[]);
ui::button(
batch,
atlas,
x,
126.0,
150.0,
bx,
by,
POPUP_BUTTON,
20.0,
&Text::translate("lanServer.port", &[]),
false,
false,
&label,
true,
hover,
);
}
self.world_options = Some(o);
}
fn draw_restrictions(&self, batch: &mut HudBatch) {
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("restrictions_screen.title", &[]);
let tw = atlas.font.width_text(&title);
batch.text_styled(
atlas,
&title,
((w - tw) / 2.0).floor(),
12.0,
u32::MAX,
true,
);
let r = Restrictions::new(&atlas.font, self.settings.chat_visibility, (w, h));
let first = batch.vertices.len();
for (line, x, y) in &r.lines {
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
}
if let Some((ax, ay)) = r.action {
let hover = ui::hovered(self.cursor, ax, ay, 200.0, 20.0);
let label = Text::translate("chat_restriction.chat_disabled_by_options.action", &[]);
ui::button(batch, atlas, ax, ay, 200.0, 20.0, &label, true, hover);
}
batch.clip_since(first, 0.0, r.area.0, w, r.area.1);
let (dx, dy) = Restrictions::done(w, h);
let hover = ui::hovered(self.cursor, dx, dy, 200.0, 20.0);
let label = Text::translate("gui.done", &[]);
ui::button(batch, atlas, dx, dy, 200.0, 20.0, &label, true, hover);
}
fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) {
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
o.scroll = o.scroll.clamp(0.0, WorldOptions::max_scroll(h));
// extractMenuBackground: the in-world background, the list
// background under the content, then the separators over it.
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
ui::list_background(batch, atlas, HEADER, h - FOOTER, true);
let title = Text::translate("options.worldOptions.title", &[]);
let tw = atlas.font.width_text(&title);
batch.text_styled(
atlas,
&title,
((w - tw) / 2.0).floor(),
12.0,
u32::MAX,
true,
);
let top = o.top();
let first = batch.vertices.len();
let x = WorldOptions::left(w);
for (key, y) in [
("options.worldOptions.general.title", GENERAL_TOP),
("options.worldOptions.multiplayer.title", MULTIPLAYER_TOP),
] {
// A FocusableTextWidget padded by 4, centred over both columns.
let t = Text::translate(key, &[]).underlined().bold();
let tw = atlas.font.width_text(&t);
let tx = x + ((308.0 - (tw + 8.0)) / 2.0).trunc() + 4.0;
batch.text_styled(atlas, &t, tx, top + y + 4.0, u32::MAX, true);
}
let inside = cursor.1 >= HEADER && cursor.1 < h - FOOTER;
for (b, bx, by, bw) in WorldOptions::buttons(w, top) {
let active = o.active(b);
let hover = active && inside && ui::hovered(cursor, bx, by, bw, 20.0);
if b == Button::Lock {
let lock = if o.locked { "locked" } else { "unlocked" };
let state = match (active, hover) {
(false, _) => "_disabled",
(true, true) => "_highlighted",
(true, false) => "",
};
let sprite = format!("gui/sprites/widget/{lock}_button{state}");
batch.sprite_scaled(atlas, &sprite, bx, by, 20.0, 20.0, u32::MAX);
continue;
}
ui::button(batch, atlas, bx, by, bw, 20.0, &o.label(b), active, hover);
}
// The port box beside the LAN button: editable only with LAN on,
// its hint the port to use (setPortError colours the text).
o.port.x = x + 158.0;
o.port.y = top + PORT_TOP;
o.port.focused = o.lan && o.port.focused;
o.port.text_color = if !o.lan {
rgba(0x70, 0x70, 0x70, 255)
} else if o.parsed_port().is_some() {
rgba(0xE0, 0xE0, 0xE0, 255)
} else {
rgba(0xDF, 0x50, 0x50, 255)
};
o.port.draw(batch, atlas, None);
if o.port.value.is_empty() && !o.port.focused {
let hint = if o.lan {
Text::literal(o.hint.to_string())
} else {
Text::translate("lanServer.port", &[])
};
// EditBox.DEFAULT_HINT_STYLE: dark gray.
batch.text_styled(
atlas,
&hint,
o.port.text_x(),
o.port.text_y(),
rgba(0x55, 0x55, 0x55, 255),
true,
);
}
batch.clip_since(first, 0.0, HEADER, w, h - FOOTER);
ui::scrollbar(
batch,
atlas,
(w / 2.0).floor() + 166.0,
HEADER,
h - FOOTER,
CONTENT,
o.scroll.trunc(),
);
ui::separators(batch, atlas, HEADER, h - FOOTER, true);
for (b, bx, by, bw) in WorldOptions::footer(w, h) {
let active = o.active(b);
let hover = active && ui::hovered(cursor, bx, by, bw, 20.0);
ui::button(batch, atlas, bx, by, bw, 20.0, &o.label(b), active, hover);
}
}
/// The mouse wheel over the screen (ScrollableLayout, 10 pixels a step).
pub(super) fn world_options_scroll(&mut self, delta: f32) {
let h = self.gui_size().1;
match self.world_options.as_mut() {
Some(o) if o.view == View::Options => {
o.scroll = (o.scroll - delta * 10.0).clamp(0.0, WorldOptions::max_scroll(h));
}
Some(o) => {
if let Some(rules) = o.rules.as_mut() {
rules.wheel(delta, h);
}
}
None => {}
}
}
pub(super) fn world_options_click(&mut self) {
let Some(mut o) = self.world_options.take() else {
return;
};
let size = self
.renderer
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let (w, h) = (b.width, b.height);
let port_x = (w / 2.0 - 154.0).floor() + 158.0;
o.port.focused = o.lan && ui::hovered(self.cursor, port_x, 126.0, 150.0, 20.0);
let hit = WorldOptions::buttons(w)
.into_iter()
.chain(WorldOptions::footer(w, h))
.find(|(button, x, y, bw)| {
o.active(*button) && ui::hovered(self.cursor, *x, *y, *bw, 20.0)
})
.map(|b| b.0);
let (w, h) = self.gui_size();
match o.view {
View::Options => {}
View::GameRules => {
let atlas = &self.atlas;
let exit = o.rules.as_mut().and_then(|rules| {
if rules.clicks_button(atlas, self.cursor, (w, h)) {
self.audio.play_button_click();
}
rules.click(atlas, self.cursor, (w, h))
});
self.world_options = Some(o);
if let Some(exit) = exit {
self.close_game_rules(exit);
}
return;
}
View::LockQuestion => {
let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h));
let hit = p
.buttons
.iter()
.position(|&(bx, by)| ui::hovered(self.cursor, bx, by, POPUP_BUTTON, 20.0));
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
// Yes: apply, then back to the pause menu; No: back to the options.
Some(0) => return self.apply_and_close_world_options(o),
Some(_) => o.view = View::Options,
None => {}
}
self.world_options = Some(o);
return;
}
View::Restrictions => {
let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h));
let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1;
let action = r.action.is_some_and(|(ax, ay)| {
in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0)
});
let (dx, dy) = Restrictions::done(w, h);
let done = ui::hovered(self.cursor, dx, dy, 200.0, 20.0);
if action || done {
self.audio.play_button_click();
o.view = View::Options;
}
self.world_options = Some(o);
if action {
// ChatRestriction.Action.GO_TO_CHAT_SETTINGS: Chat Settings,
// which returns to the screen behind RestrictionsScreen.
self.open_options_at(false, horizon_client::options_ui::Page::Chat);
self.options_to_world_options = true;
}
return;
}
}
let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER;
o.port.focused = o.lan
&& inside
&& ui::hovered(
self.cursor,
WorldOptions::left(w) + 158.0,
o.top() + PORT_TOP,
150.0,
20.0,
);
let hit = o.hit(self.cursor, (w, h));
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
Some(Button::DefaultMode) => o.default_mode = (o.default_mode + 1) % 4,
Some(Button::PersonalMode) => o.personal_mode = (o.personal_mode + 1) % 4,
Some(Button::Cheats) => o.cheats = !o.cheats,
Some(Button::Cheats) => {
o.cheats = !o.cheats;
// updatePermissionDependentButtons: without commands both
// game modes return to the world's default.
if !o.cheats {
o.default_mode = o.initial.default_mode;
o.personal_mode = o.default_mode;
}
}
Some(Button::Difficulty) => o.difficulty = (o.difficulty + 1) % 4,
Some(Button::Lock) => o.locked = !o.locked,
Some(Button::Restrictions) => o.view = View::Restrictions,
Some(Button::GameRules) => {
o.rules = Some(RulesScreen::new(&self.ui.rules));
o.view = View::GameRules;
}
Some(Button::Lan) => {
o.lan = !o.lan;
o.port.focused = false;
@@ -301,19 +798,22 @@ impl Game<'_> {
self.close_world_options();
return;
}
Some(Button::Apply) => {
let wanted = o.snapshot();
let before = o.initial.clone();
self.world_options = Some(o);
self.apply_world_options(&before, &wanted);
self.close_world_options();
return;
}
// A new lock asks first.
Some(Button::Apply) if o.locked != o.initial.locked => o.view = View::LockQuestion,
Some(Button::Apply) => return self.apply_and_close_world_options(o),
None => {}
}
self.world_options = Some(o);
}
fn apply_and_close_world_options(&mut self, o: WorldOptions) {
let wanted = o.snapshot();
let before = o.initial.clone();
self.world_options = Some(o);
self.apply_world_options(&before, &wanted);
self.close_world_options();
}
pub(super) fn world_options_key(&mut self, event: &KeyEvent) {
if event.state != winit::event::ElementState::Pressed {
return;
@@ -326,7 +826,22 @@ impl Game<'_> {
let Some(o) = self.world_options.as_mut() else {
return;
};
if !o.port.focused {
if let Some(rules) = o.rules.as_mut().filter(|r| r.typing()) {
match shortcut {
Some(shortcut) => rules.edit(|b| {
b.shortcut(shortcut, &mut self.clipboard);
}),
None => {
let mut handled = false;
rules.edit(|b| handled = b.key(key, ctrl, false));
if !handled && !ctrl {
self.world_options_text(event.text.as_deref());
}
}
}
return;
}
if !o.port.focused || o.view != View::Options {
return;
}
if let Some(shortcut) = shortcut {
@@ -340,6 +855,25 @@ impl Game<'_> {
/// Digits typed into the port field (the keyboard, or a controller's
/// on-screen keyboard), and its backspace.
pub(super) fn world_options_text(&mut self, text: Option<&str>) {
if let Some(rules) = self
.world_options
.as_mut()
.and_then(|o| o.rules.as_mut())
.filter(|r| r.typing())
{
match text {
Some(text) => {
let typed: String = text.chars().filter(|c| !c.is_control()).collect();
if !typed.is_empty() {
rules.edit(|b| b.insert_text(&typed));
}
}
None => rules.edit(|b| {
b.key(winit::keyboard::KeyCode::Backspace, false, false);
}),
}
return;
}
let Some(o) = self.world_options.as_mut().filter(|o| o.port.focused) else {
return;
};
@@ -362,6 +896,10 @@ impl Game<'_> {
let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3];
self.as_console(|g| g.run_command(&format!("difficulty {name}")));
}
// ServerboundLockDifficultyPacket(true): MinecraftServer.setDifficultyLocked.
if wanted.locked && !before.locked {
self.level.difficulty_locked = true;
}
if wanted.default_mode != before.default_mode {
self.set_default_game_mode(wanted.default_mode);
}
@@ -390,3 +928,109 @@ impl Game<'_> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn options(cheats: bool, hardcore: bool) -> WorldOptions {
let mut o = WorldOptions {
default_mode: 1,
personal_mode: 1,
cheats,
difficulty: 2,
lan: false,
port: EditBox::new(0.0, 0.0, 150.0, 20.0),
hint: 25565,
guest_commands: false,
force: true,
hardcore,
difficulty_locked: false,
locked: hardcore,
scroll: 0.0,
view: View::Options,
rules: None,
initial: Snapshot {
default_mode: 0,
personal_mode: 0,
cheats: false,
difficulty: 0,
locked: false,
lan: false,
port: 0,
guest_commands: false,
force: false,
},
};
o.initial = o.snapshot();
o
}
#[test]
fn layout_follows_the_header_footer_and_grids() {
let at = |b: Button| {
let o = options(true, false);
WorldOptions::buttons(427.0, o.top())
.into_iter()
.chain(WorldOptions::footer(427.0, 240.0))
.find(|e| e.0 == b)
.map(|(_, x, y, w)| (x, y, w))
.unwrap()
};
// Header 33, content padding 8, heading 17, rows 4 apart.
assert_eq!(at(Button::DefaultMode), (59.0, 62.0, 308.0));
assert_eq!(at(Button::Cheats), (59.0, 110.0, 150.0));
assert_eq!(at(Button::Difficulty), (217.0, 110.0, 130.0));
assert_eq!(at(Button::Lock), (347.0, 110.0, 20.0));
assert_eq!(at(Button::Restrictions), (217.0, 134.0, 150.0));
// The Multiplayer grid 24 below: padding, spacing, padding.
assert_eq!(at(Button::Lan), (59.0, 199.0, 150.0));
assert_eq!(at(Button::Force), (217.0, 223.0, 150.0));
assert_eq!(at(Button::Apply), (59.0, 213.0, 150.0));
// 218 pixels of content over 174 between the separators.
assert_eq!(WorldOptions::max_scroll(240.0), 44.0);
assert_eq!(WorldOptions::max_scroll(400.0), 0.0);
}
#[test]
fn buttons_follow_commands_hardcore_and_lan() {
let o = options(true, false);
assert!(o.active(Button::DefaultMode) && o.active(Button::Difficulty));
assert!(!o.active(Button::CommandAccess) && !o.active(Button::Force));
assert!(!o.active(Button::Apply));
assert!(o.active(Button::GameRules));
let mut o = options(false, false);
assert!(!o.active(Button::DefaultMode) && !o.active(Button::PersonalMode));
// Game Rules follows the commands the player has, not the switch.
assert!(!o.active(Button::GameRules));
o.cheats = true;
assert!(!o.active(Button::GameRules));
let o = options(true, true);
assert!(!o.active(Button::GameRules));
let o = options(false, true);
assert!(!o.active(Button::Cheats) && !o.active(Button::Difficulty));
assert!(!o.active(Button::Force));
// Scrolled widgets only take clicks between the separators.
let mut o = options(true, false);
o.scroll = 44.0;
assert_eq!(o.hit((100.0, 30.0), (427.0, 240.0)), None);
assert_eq!(o.hit((100.0, 70.0), (427.0, 240.0)), Some(Button::Cheats));
}
#[test]
fn the_lock_follows_the_level_and_counts_as_a_change() {
let mut o = options(true, false);
assert!(o.active(Button::Lock) && o.active(Button::Restrictions));
assert!(!o.locked && !o.changed());
// The wanted lock alone enables Apply (hasSettingsChanges).
o.locked = true;
assert!(o.changed() && o.active(Button::Difficulty));
// A locked level: neither the difficulty nor the lock.
let mut o = options(true, false);
o.difficulty_locked = true;
assert!(!o.active(Button::Lock) && !o.active(Button::Difficulty));
// Hardcore shows the lock closed, and inactive.
let o = options(true, true);
assert!(o.locked && !o.active(Button::Lock));
}
}
+1 -1
View File
@@ -283,7 +283,7 @@ impl Game<'_> {
}
/// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots.
pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let white = atlas.font.white();
let uv = [
[white.u0, white.v1],
+3 -3
View File
@@ -174,7 +174,7 @@ impl Game<'_> {
if below.sturdy_full >> 1 & 1 == 0 {
continue;
}
if let Some(fire) = self.res.assets.registry.default_state(name) {
if let Some(fire) = self.pack.assets.registry.default_state(name) {
let _ = self.level_set(p, fire);
}
}
@@ -239,7 +239,7 @@ impl Game<'_> {
if !self.res.facts.get(state).name.ends_with("lightning_rod") {
return;
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
if let Some(mut s) = registry.state(state).cloned() {
s.properties.insert("powered".into(), "true".into());
if let Some(powered) = registry.id(&s) {
@@ -348,7 +348,7 @@ impl Game<'_> {
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
/// segments of 16 blocks, from the bolt's seed.
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let white = self.res.atlas.font.white();
let white = self.atlas.font.white();
let uv = [white.u0, white.v0];
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
+3 -3
View File
@@ -198,8 +198,8 @@ impl Game<'_> {
.map(|l| (banners.banner_texture(&l.pattern), l.color.to_string()))
.collect();
horizon_client::item_render::gui::draw_banner_result(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
batch,
x,
y,
@@ -217,7 +217,7 @@ impl Game<'_> {
draws: &[ScreenDraw],
background: bool,
) -> Option<Vec<(String, u32)>> {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let mut tooltip = None;
let mut sheet: Option<String> = None;
for d in draws {
+3 -3
View File
@@ -363,7 +363,7 @@ impl Game<'_> {
world: &self.world,
behaviours: &self.res.behaviours,
items: &self.res.items,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
brewing: Some(&self.res.stations.brewing),
bone_meal: bone_meal(),
}
@@ -500,7 +500,7 @@ impl Game<'_> {
/// Every hopper's `pushItemsTick`, in a stable position order.
pub(super) fn tick_hoppers(&mut self) -> Result<()> {
let hopper = self
.res
.pack
.assets
.registry
.default_state("minecraft:hopper")
@@ -833,7 +833,7 @@ impl Game<'_> {
let Some(screen) = self.machine_screen() else {
return false;
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let key_is_cart = self
.container
.is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y);
@@ -33,7 +33,7 @@ fn recipe_matches(condition: &Value, id: &str) -> bool {
impl Game<'_> {
/// `Level.setBlock` of one boolean property of the block at `pos`.
fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let old = self.world.block(pos.0, pos.1, pos.2);
let Some(mut state) = registry.state(old).cloned() else {
return;
@@ -254,7 +254,7 @@ impl Game<'_> {
// 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;
let atlas = &self.atlas;
let grey = rgba(64, 64, 64, 255);
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
+3 -4
View File
@@ -789,7 +789,6 @@ impl Game<'_> {
}
let slot = self.maps.slots.last()?.1;
let rect = self
.res
.atlas
.sprites
.get(&format!("horizon/map{slot}"))
@@ -798,7 +797,7 @@ impl Game<'_> {
if m.texture_dirty {
m.texture_dirty = false;
let rgba: Vec<u8> = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect();
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -856,7 +855,7 @@ impl Game<'_> {
.map(|m| m.decorations.clone())
.unwrap_or_default();
for (i, d) in decorations.iter().enumerate() {
let Some(s) = self.res.atlas.sprites.get(d.sprite).copied() else {
let Some(s) = self.atlas.sprites.get(d.sprite).copied() else {
continue;
};
let dm = glam::Mat4::from_translation(glam::Vec3::new(
@@ -932,7 +931,7 @@ impl Game<'_> {
} else {
"map/map_background"
};
if let Some(r) = self.res.atlas.sprites.get(background).copied() {
if let Some(r) = self.atlas.sprites.get(background).copied() {
for (c, uv) in [
([-7.0, 135.0, 0.0], [r.u0, r.v1]),
([135.0, 135.0, 0.0], [r.u1, r.v1]),
+7 -8
View File
@@ -220,7 +220,7 @@ impl Game<'_> {
) {
return None;
}
let s = self.res.assets.registry.state(state)?;
let s = self.pack.assets.registry.state(state)?;
let shape = Shape::parse(s.properties.get("shape").map_or("", String::as_str));
let powered = s.properties.get("powered").is_some_and(|v| v == "true");
Some(Rail {
@@ -1148,16 +1148,16 @@ impl Game<'_> {
diffuse: bool,
out: &mut Vec<Vertex>,
) {
let Ok(models) = self.res.assets.model_catalog.collect_seeded(state, seed) else {
let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else {
return;
};
for (_, model) in &models {
for face in &model.faces {
let Some(s) = self
.res
.pack
.layer_names
.get(&face.layer)
.and_then(|n| self.res.atlas.sprites.get(n))
.and_then(|n| self.atlas.sprites.get(n))
else {
continue;
};
@@ -1203,7 +1203,7 @@ impl Game<'_> {
}
}
fn display_state(&self, c: &Minecart) -> Option<BlockStateId> {
let registry = &self.res.assets.registry;
let registry = &self.pack.assets.registry;
let with = |name: &str, props: &[(&str, &str)]| {
let mut s = registry.state(registry.default_state(name)?)?.clone();
for (k, v) in props {
@@ -1236,7 +1236,6 @@ impl Game<'_> {
continue;
};
let Some(uv) = self
.res
.atlas
.sprites
.get("entity/minecart/minecart")
@@ -1343,12 +1342,12 @@ impl Game<'_> {
game_time: self.world.game_time,
max_y: self.dim.max_y(),
world: &self.world,
sprites: &self.res.atlas.sprites,
sprites: &self.atlas.sprites,
nether: self.dim == super::Dim::Nether,
lid: &lid,
sign: &|_| None,
banner: &|_| Vec::new(),
glyph: &|c| self.res.atlas.glyph_cell(c),
glyph: &|c| self.atlas.glyph_cell(c),
};
self.res
.block_entity_render
+3 -3
View File
@@ -78,7 +78,7 @@ impl Game<'_> {
let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else {
return;
};
let Some(r) = self.res.atlas.sprites.get("entity/guardian_elder").copied() else {
let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else {
return;
};
let age = (APPARITION_TICKS - left) as f32 + alpha as f32;
@@ -147,7 +147,7 @@ impl Game<'_> {
return;
};
let m = banner_matrix(head);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
// BannerRenderer: the flag sways with a per-banner phase.
let phase =
@@ -187,7 +187,7 @@ impl Game<'_> {
) {
for (corners, shade, side) in FACES {
let name = cube.sprites[usize::from(side)];
let Some(r) = self.res.atlas.sprites.get(name).copied() else {
let Some(r) = self.atlas.sprites.get(name).copied() else {
continue;
};
let tint = if side == 0 { cube.tint } else { 0xFF_FFFF };
+79 -3
View File
@@ -4,6 +4,7 @@
//! every hook here returns after one check.
use super::{Game, Screen};
use horizon_client::{
command::{Dispatcher, vanilla},
extras::Corner,
extras_hud::{self, Corners},
hud::HudBatch,
@@ -23,19 +24,83 @@ pub(super) struct ModsState {
pub(super) dev: Vec<PathBuf>,
/// When dev mods were last checked for a rebuild.
checked: Option<Instant>,
/// The chat's command tree while a running mod owns commands.
tree: Option<Dispatcher>,
}
impl ModsState {
/// The chat's command tree: vanilla's, plus the running mods' commands.
pub(super) fn dispatcher(&self) -> &Dispatcher {
self.tree
.as_ref()
.unwrap_or_else(|| vanilla::game_dispatcher())
}
}
/// How often dev mods are checked for a rebuild.
const RELOAD_CHECK: Duration = Duration::from_secs(1);
/// A vanilla command name: mods may not take it.
fn vanilla_command(name: &str) -> bool {
let d = horizon_client::command::vanilla::game_dispatcher();
let d = vanilla::game_dispatcher();
d.nodes[0]
.children
.iter()
.any(|&c| d.nodes[c].name() == name)
}
/// `root` with the content mods that are on layered over it
/// (docs/modpacks.md): their blocks, items, data and assets. Read once at
/// start, before the resources load; a mod whose content is refused is left
/// out here and its row on the Mods page says why.
pub(super) fn content_root(
root: &std::path::Path,
enabled: &std::collections::BTreeSet<String>,
dev: &[std::path::PathBuf],
) -> std::path::PathBuf {
use horizon_client::mod_content::{self, ContentMod};
use horizon_mods::{Capability, Content, Package};
let here = std::env::current_dir().unwrap_or_default();
let mut paths = horizon_mods::find(&here.join(mod_list::DIR));
paths.retain(|p| !dev.contains(p));
paths.extend(dev.iter().cloned());
let mut mods: Vec<ContentMod> = Vec::new();
for path in &paths {
let Ok(package) = Package::read(path) else {
continue;
};
let m = &package.manifest;
let on = enabled.contains(&m.id) || dev.contains(path);
if !on
|| !m.capabilities.contains(&Capability::Registries)
|| mods.iter().any(|c| c.id == m.id)
{
continue;
}
match Content::read(path, m) {
Ok(content) => mods.push(ContentMod {
id: m.id.clone(),
content,
}),
Err(e) => log::warn!("Horizon: mod {} content not loaded: {e}", m.id),
}
}
match mod_content::resource_root(root, &mods, &here.join(".horizon-cache")) {
Ok(out) => {
if out != root {
log::info!(
"Horizon: content from {} mod(s) in {}",
mods.len(),
out.display()
);
}
out
}
Err(e) => {
log::warn!("Horizon: content mods not loaded: {e}");
root.to_owned()
}
}
}
impl Game<'_> {
/// Reads `horizon-mods/` and the dev mods, and starts the ones turned on.
pub(super) fn start_mods(&mut self) {
@@ -55,6 +120,7 @@ impl Game<'_> {
let mods = Mods::load(&paths, on, vanilla_command);
self.mods.mods = mods;
self.list_mods();
self.sync_mod_commands();
self.show_mod_output();
}
/// The Mods page's rows, from what loaded.
@@ -97,6 +163,14 @@ impl Game<'_> {
})
.collect();
}
/// The chat's tree after the running mods changed.
fn sync_mod_commands(&mut self) {
let mut names = self.mods.mods.commands().peekable();
self.mods.tree = names
.peek()
.is_some()
.then(|| vanilla::game_dispatcher().with_mod_commands(names));
}
/// After the options changed: restart the mods if the list of the ones
/// turned on did.
pub(super) fn sync_mods(&mut self) {
@@ -160,6 +234,7 @@ impl Game<'_> {
self.mods.checked = Some(Instant::now());
if self.mods.mods.reload_changed(vanilla_command) {
self.list_mods();
self.sync_mod_commands();
self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY));
}
}
@@ -201,6 +276,7 @@ impl Game<'_> {
Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED),
Output::Stopped { name, reason } => {
self.list_mods();
self.sync_mod_commands();
Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED)
}
};
@@ -208,7 +284,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
.add(&self.atlas, line, None, self.ticks, focused);
}
}
/// The mods' HUD panels, stacked with the extras in their corners.
@@ -229,7 +305,7 @@ impl Game<'_> {
.iter()
.map(|l| (l.text.as_str(), l.color))
.collect();
extras_hud::draw_lines(batch, &self.res.atlas, corners, corner, &lines);
extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines);
}
}
}
+2 -2
View File
@@ -283,7 +283,7 @@ impl Game<'_> {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_region(
atlas,
"gui/container/horse",
@@ -376,7 +376,7 @@ impl Game<'_> {
m.hurt_time = 0;
m.death_time = 0;
let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let mut verts = Vec::new();
horizon_client::mobs::render::render_with(
+1 -1
View File
@@ -457,7 +457,7 @@ impl Game<'_> {
return (0, false);
};
let m = &self.mobs[i];
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health);
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health);
horizon_client::hud_layout::paint(batch, atlas, &draws);

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