Merge main into #1205: keep push_tests next to teams_tests and sensor_scan_tests

#1200 and the teams change appended test modules at the same place as this
branch's push_tests. Main's modules are kept as they are and push_tests
follows them unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-22 19:57:27 +02:00
250 changed files with 17519 additions and 2031 deletions
+3
View File
@@ -116,6 +116,9 @@ jobs:
# Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository
# variable, not a secret. Unset, the launcher says sign-in is not configured.
HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }}
# The mod browser's CurseForge source (docs/mod-browser.md#curseforge): a repository secret. Unset, the
# launcher searches Modrinth only.
HORIZON_CURSEFORGE_API_KEY: ${{ secrets.HORIZON_CURSEFORGE_API_KEY }}
# The release's version and tag, built in (launcher/src/backend.rs VERSION and own_tag: the tag says which
# line it is on, docs/versioning.md); a launcher branch's build keeps Cargo.toml's.
HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }}
+12 -9
View File
@@ -1,17 +1,20 @@
name: promote
# Beta game releases become stable (docs/release-flow.md, "Channels"): every 30 minutes tools/release_channels.py
# promotes the newest beta that has been out 6 hours, passed its release smoke test and isn't covered by an issue
# labelled release-blocker. By hand, from GitHub's app too (Actions > promote > Run workflow):
# gh workflow run promote -f tag=v2026.10.19.03 # that beta now, without the wait
# gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without its smoke test
# gh workflow run promote -f dry_run=true # say what would be promoted
# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in
# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then,
# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha
# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are
# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once.
# By hand, from GitHub's app too (Actions > promote > Run workflow):
# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00
# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test
# gh workflow run promote -f dry_run=true # say what would be promoted
# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it
# still holds the betas published before it closed. The issue's text is never read (its author could edit it).
# When the oldest waiting beta is 24 hours old, an issue "Promotion to stable has stalled" says so; it closes itself
# after the next promotion.
# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable
# has stalled" says so; it closes itself after the next promotion.
on:
schedule:
- cron: '13,43 * * * *'
- cron: '7,37 20-21 * * *'
workflow_dispatch:
inputs:
tag:
+19 -7
View File
@@ -1,14 +1,14 @@
name: release
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes
# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now.
# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes
# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now.
# RELEASES_PAUSED=1 (repository variable) stops them.
# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
# publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated
# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes
# stable after 6 hours. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with
# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with
# Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain
# (packaging/macos/README.md); unset (forks), ad hoc.
# gh workflow run release --ref <branch> # dry run: builds and notes, publishes nothing
@@ -45,6 +45,7 @@ jobs:
outputs:
release: ${{ steps.decide.outputs.release }}
tag: ${{ steps.decide.outputs.tag }}
version: ${{ steps.decide.outputs.version }}
head: ${{ steps.decide.outputs.head }}
dry_run: ${{ steps.mode.outputs.dry_run }}
steps:
@@ -65,6 +66,9 @@ jobs:
run: |
python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json
echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY"
# The version the programs are built with (docs/versioning.md): the tag without its v.
tag=$(jq -r '.tag' decision.json)
echo "version=${tag#v}" >> "$GITHUB_OUTPUT"
# A dry run builds whatever the decision, to test the builds.
if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi
@@ -99,6 +103,9 @@ jobs:
timeout-minutes: ${{ matrix.mac && 60 || 40 }}
env:
RUSTFLAGS: ${{ matrix.rustflags }}
# The release's version, built in (horizon_core::release): --version, user agents, crash reports and
# telemetry say it. No version-bump commits.
HORIZON_VERSION: ${{ needs.decide.outputs.version }}
defaults:
run:
shell: bash
@@ -162,9 +169,13 @@ jobs:
bin=target/release
"$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources'
"$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null
"$bin/horizon-prepare${{ matrix.exe }}" --version
"$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir'
"$bin/horizon-server${{ matrix.exe }}" --version
# The version is the release's.
for binary in horizon-prepare horizon-server; do
out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r')
echo "$out"
[[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; }
done
- name: Tools from the runner
if: runner.environment == 'self-hosted'
run: bash tools/ci/runner-env.sh
@@ -245,7 +256,7 @@ jobs:
folder="dist/${{ matrix.server_dir }}"
python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare"
"$folder/horizon-engine" --help | grep -q -- '--resources'
"$folder/horizon-server" --version
[[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]]
cd dist
rm -f "${{ matrix.server_asset }}"
tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}"
@@ -338,7 +349,8 @@ jobs:
run: |
signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig)
smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json)
# A beta (pre-release): promote.yml makes it stable and latest after 6 hours (docs/release-flow.md).
# A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion
# (docs/release-flow.md).
gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
--notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \
dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \
+3 -2
View File
@@ -42,8 +42,9 @@ log = "0.4"
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
horizon-theme = { path = "../horizon-theme" }
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md); `live` is
# the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] }
horizon-bench = { path = "../horizon-bench" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
@@ -14,6 +14,8 @@ use std::{
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
};
/// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only).
const STAGE: [f32; 2] = [0.25, 0.5];
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let root = Path::new(&args[1]);
@@ -47,7 +49,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.iter()
.any(|(_, m)| m.faces.iter().any(|f| f.translucent));
for (_, m) in models {
breaking::geometry(m, origin, translucent, &mut vertices);
breaking::geometry(m, origin, translucent, STAGE, &mut vertices);
}
}
let quads: Vec<_> = vertices
@@ -58,7 +60,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
q.iter()
.map(|v| {
assert_eq!(v.color, 0xffff_ffff);
assert_eq!(v.light, 240 | (240 << 8));
assert_eq!(v.light, breaking::stage_light(STAGE));
assert_eq!(v.layer, if translucent { 12 } else { 11 });
[v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]]
})
@@ -82,12 +82,19 @@ fn main() -> horizon_client::Result<()> {
let brewing = horizon_client::brewing::Brewing::load(root, &items);
// The inventory menu never reads banner patterns.
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
let enchantments = horizon_client::enchant::Enchantments::default();
let names = horizon_client::creative::Names::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: None,
maps: None,
};
let mut out = String::new();
for line in input.lines() {
@@ -102,6 +102,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
equipment: Default::default(),
health: 20.0,
attributes: Vec::new(),
bed: None,
living_flags: 0,
};
loop {
+106 -4
View File
@@ -11,8 +11,41 @@ use horizon_client::{
items::Items,
menu::{Env, Input, Kind, Menu},
};
use horizon_protocol::registry::Ids;
use serde_json::Value;
use std::{fs, path::Path};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
fs,
path::Path,
};
/// The case's maps: (locked, scale) by id, and the next free id.
#[derive(Default)]
struct CaseMaps {
maps: RefCell<HashMap<i32, (bool, u8)>>,
next: Cell<i32>,
}
impl horizon_client::menu::Maps for CaseMaps {
fn state(&self, id: i32) -> Option<(bool, u8)> {
self.maps.borrow().get(&id).copied()
}
/// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`.
fn derive(&self, id: i32, scale: bool) -> Option<i32> {
let (_, s) = self.state(id)?;
let new = self.next.get();
self.next.set(new + 1);
let made = if scale {
(false, (s + 1).min(4))
} else {
(true, s)
};
self.maps.borrow_mut().insert(new, made);
Some(new)
}
}
fn state(menu: &Menu) -> String {
let slots: Vec<String> = (0..menu.slot_count())
@@ -24,13 +57,21 @@ fn state(menu: &Menu) -> String {
.iter()
.map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref())))
.collect();
format!(
let line = format!(
"{} | {} |{data} | {} | {}",
slots.join(" "),
canon_stack(menu.carried.as_ref()),
menu.drops.join(";"),
equipped.join(";")
)
);
if menu.kind() != Kind::Lectern {
return line;
}
// No inventory slots: the inventory Take Book fills.
let items: String = (0..36)
.map(|i| format!(" {}", canon_stack(menu.player_item(i))))
.collect();
format!("{line} | inv{items}")
}
fn main() -> horizon_client::Result<()> {
@@ -44,13 +85,28 @@ fn main() -> horizon_client::Result<()> {
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::load(root);
let station_recipes = horizon_client::stations::StationRecipes::load(root, &items);
let enchantments = horizon_client::enchant::Enchantments::load(root);
let names = horizon_client::creative::Names::load(root);
let case_maps = CaseMaps::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: None,
maps: Some(&case_maps),
};
// The mob effects' network ids (BeaconMenu.encodeEffect).
let builtin = horizon_protocol::registry::Builtin::find(root)
.and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok());
let effects = builtin
.as_ref()
.and_then(|b| b.get("minecraft:mob_effect"))
.cloned();
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
@@ -68,15 +124,41 @@ fn main() -> horizon_client::Result<()> {
.unwrap_or(name),
)
.ok_or("menu kind")?;
// [id, scale, locked] each; the level's new maps from 1000.
case_maps.next.set(1000);
*case_maps.maps.borrow_mut() = case["maps"]
.as_array()
.into_iter()
.flatten()
.map(|m| {
let id = m[0].as_i64().unwrap_or(0) as i32;
(
id,
(
m[2].as_bool().unwrap_or(false),
m[1].as_u64().unwrap_or(0) as u8,
),
)
})
.collect();
let mut menu = Menu::new(kind);
menu.creative = case["creative"].as_bool().unwrap_or(false);
menu.levels = case["levels"].as_i64().unwrap_or(0) as i32;
for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() {
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
}
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
for (i, item) in case["inventory"]
.as_array()
.into_iter()
.flatten()
.enumerate()
{
menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?);
}
menu.settle(&env);
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
menu.set_data(i, v.as_i64().unwrap_or(0) as i32);
}
let mut furnace = furnace_kind.map(|kind| Furnace {
kind,
@@ -100,6 +182,26 @@ fn main() -> horizon_client::Result<()> {
out += &format!("{}\n", state(&menu));
continue;
}
// ServerboundRenameItemPacket: AnvilMenu.setItemName.
"RENAME" => {
menu.rename(&env, op[3].as_str().unwrap_or_default());
out += &format!("{}\n", state(&menu));
continue;
}
// ServerboundSetBeaconPacket: BeaconMenu.updateEffects.
"SET_BEACON" => {
fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> {
let name = v.as_str()?;
Some((ids?.id(name)?, name))
}
let (primary, secondary) = (
power(effects.as_ref(), &op[3]),
power(effects.as_ref(), &op[4]),
);
menu.beacon_update(&env, primary, secondary);
out += &format!("{}\n", state(&menu));
continue;
}
// ServerboundContainerSlotStateChangedPacket.
"SLOT_STATE" => {
if (0..9).contains(&slot) {
@@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> {
nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position),
others: $snapshot,
others_grid: $grid,
others_index: None,
daylight: (world.day_time.rem_euclid(24000)) < 12000,
game_time: world.game_time,
day_time: world.day_time,
@@ -112,21 +112,26 @@ fn state(s: &ParticleSnapshot) -> String {
}
out
}
fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result<World> {
fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Result<World> {
let mut world = World::new(facts.air, 0);
let stone = assets
.registry
.default_state("minecraft:stone")
.ok_or("missing stone")?;
let state = |name: &str| assets.registry.default_state(name).ok_or("missing block");
let (stone, still) = (state("minecraft:stone")?, state("minecraft:water")?);
for cz in -3..=2 {
for cx in -3..=2 {
world
.chunks
.insert((cx, cz), Arc::new(Chunk::empty(cx, cz)));
if floor {
for z in 0..16 {
for x in 0..16 {
world.set(cx * 16 + x, 63, cz * 16 + z, stone)?;
for z in 0..16 {
for x in 0..16 {
let (x, z) = (cx * 16 + x, cz * 16 + z);
if floor {
world.set(x, 63, z, stone)?;
}
// The oracle's water: still sources from y 64 to 67.
if water {
for y in 64..=67 {
world.set(x, y, z, still)?;
}
}
}
}
@@ -142,8 +147,10 @@ fn main() -> Result<()> {
let facts = BlockFacts::load(root, assets.registry)?;
let collision = collisions::load(root, assets.registry)?;
let worlds = [
world(&assets, &facts, false)?,
world(&assets, &facts, true)?,
world(&assets, &facts, false, false)?,
world(&assets, &facts, true, false)?,
world(&assets, &facts, false, true)?,
world(&assets, &facts, true, true)?,
];
let mut engine = ParticleEngine::new(root, &HashMap::new());
for (ty, item) in [
@@ -174,7 +181,8 @@ fn main() -> Result<()> {
engine.requested = Some(Vec::new());
engine.sounds.clear();
let level = ParticleLevel {
world: &worlds[usize::from(case["floor"].as_bool() == Some(true))],
world: &worlds[usize::from(case["floor"].as_bool() == Some(true))
+ 2 * usize::from(case["water"].as_bool() == Some(true))],
facts: &facts,
collision: &collision,
player: None,
@@ -38,12 +38,19 @@ fn main() -> horizon_client::Result<()> {
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
let enchantments = horizon_client::enchant::Enchantments::default();
let names = horizon_client::creative::Names::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: None,
maps: None,
};
let mut out = String::new();
for (line, order) in cases.lines().zip(orders.lines()) {
@@ -239,10 +239,12 @@ fn main() -> horizon_client::Result<()> {
let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?;
let items = Items::catalog(root)?;
let enchantments = Enchantments::load(root);
let names = horizon_client::creative::Names::default();
let trades = Trades::load(root);
let recipes = horizon_client::crafting::Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::load(root);
let station_recipes = horizon_client::stations::StationRecipes::default();
let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)?
.types
.into_iter()
@@ -378,7 +380,11 @@ fn main() -> horizon_client::Result<()> {
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: Some(&env_trade),
maps: None,
};
trade(&mut out, name, &kv, &mut world, &env, origin)?;
}
+262
View File
@@ -53,6 +53,10 @@ pub struct Tree {
pub by_id: HashMap<String, usize>,
/// trigger id -> (advancement index, criterion index).
pub by_trigger: HashMap<String, Vec<(usize, usize)>>,
/// `recipe_unlocked` criteria by the recipe they name (`index_recipes`);
/// those naming none in `recipes_any`.
by_recipe: HashMap<String, Vec<(usize, usize)>>,
recipes_any: Vec<(usize, usize)>,
}
fn frame(v: &Value) -> Frame {
match v.as_str() {
@@ -93,12 +97,111 @@ impl Tree {
tree.list.push(a);
}
}
tree.index_recipes();
tree
}
/// Index the `recipe_unlocked` criteria by recipe: a grant that unlocks
/// twenty recipes tested every one of the ~1,300 recipe advancements'
/// criteria for each (several ms in one tick).
pub fn index_recipes(&mut self) {
self.by_recipe.clear();
self.recipes_any.clear();
for &(ai, ci) in self
.by_trigger
.get("minecraft:recipe_unlocked")
.into_iter()
.flatten()
{
match self.list[ai].criteria[ci].conditions["recipes"].as_str() {
Some(r) => self
.by_recipe
.entry(r.to_owned())
.or_default()
.push((ai, ci)),
None => self.recipes_any.push((ai, ci)),
}
}
}
/// The `recipe_unlocked` criteria that could pass for `recipe`, in tree
/// order (the others name another recipe).
pub fn recipe_criteria(&self, recipe: &str) -> Vec<(usize, usize)> {
let mut out = self.recipes_any.clone();
out.extend(self.by_recipe.get(recipe).into_iter().flatten());
out.sort_unstable();
out
}
pub fn get(&self, id: &str) -> Option<&Advancement> {
self.by_id.get(id).map(|&i| &self.list[i])
}
}
/// The `inventory_changed` criteria by the items they need. A criterion whose
/// item predicates include one limited to some items (an id, a `#tag`, a
/// list) can only pass with one of those in the inventory, so an inventory
/// change tests only the criteria of the items it holds, plus those that
/// need no particular item. The same answers as testing them all: the ~1,300
/// recipe advancements each have one, and testing every one of them cost a
/// player 1–4 ms on every tick its inventory changed.
#[derive(Default)]
pub struct InventoryIndex {
by_item: HashMap<String, Vec<(usize, usize)>>,
any: Vec<(usize, usize)>,
}
impl InventoryIndex {
/// `tag` gives a `#tag`'s item ids (none for a tag that doesn't exist,
/// which matches nothing).
pub fn build<'t>(tree: &Tree, tag: impl Fn(&str) -> Vec<&'t str>) -> Self {
fn ids<'t>(v: &Value, tag: &impl Fn(&str) -> Vec<&'t str>, out: &mut Vec<String>) {
match v {
Value::String(s) => match s.strip_prefix('#') {
Some(t) => out.extend(tag(t).into_iter().map(str::to_owned)),
None => out.push(s.clone()),
},
Value::Array(a) => a.iter().for_each(|x| ids(x, tag, out)),
_ => {}
}
}
let mut index = Self::default();
let Some(list) = tree.by_trigger.get("minecraft:inventory_changed") else {
return index;
};
for &(ai, ci) in list {
let items = &tree.list[ai].criteria[ci].conditions["items"];
// `id_matches`: only a string or a list limits the items.
let limited = items.as_array().and_then(|a| {
a.iter()
.map(|p| &p["items"])
.find(|v| v.is_string() || v.is_array())
});
match limited {
Some(v) => {
let mut out = Vec::new();
ids(v, &tag, &mut out);
out.sort();
out.dedup();
for id in out {
index.by_item.entry(id).or_default().push((ai, ci));
}
}
None => index.any.push((ai, ci)),
}
}
index
}
/// The criteria an inventory holding these item ids could pass, in
/// tree order.
pub fn candidates<'a>(&self, held: impl IntoIterator<Item = &'a str>) -> Vec<(usize, usize)> {
let mut out = self.any.clone();
for id in held {
if let Some(list) = self.by_item.get(id) {
out.extend_from_slice(list);
}
}
out.sort_unstable();
out.dedup();
out
}
}
fn collect(root: &Path, dir: &Path, ns: &str, out: &mut Vec<(String, std::path::PathBuf)>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
@@ -992,6 +1095,77 @@ impl Tree {
#[cfg(test)]
mod tests {
use super::*;
/// The criteria an inventory change and a recipe unlock test, on vanilla's tree:
/// `cargo test -p horizon-client --lib -- --ignored --nocapture index_on_vanilla_tree`
/// with HORIZON_RESOURCES set to the prepared resources.
#[test]
#[ignore = "needs the prepared resources"]
fn index_on_vanilla_tree() {
let Some(root) = std::env::var_os("HORIZON_RESOURCES").map(std::path::PathBuf::from) else {
return;
};
let data = root.join("data");
let t = std::time::Instant::now();
let tree = Tree::load(&data);
let load = t.elapsed();
let tags = data.join("minecraft/tags/item");
let tag_items: HashMap<String, Vec<String>> = std::fs::read_dir(&tags)
.into_iter()
.flatten()
.flatten()
.filter_map(|e| {
let v: Value =
serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok()?;
let name = format!("minecraft:{}", e.path().file_stem()?.to_string_lossy());
let values = v["values"]
.as_array()?
.iter()
.filter_map(|x| x.as_str().map(str::to_owned));
Some((name, values.collect()))
})
.collect();
let t = std::time::Instant::now();
let index = InventoryIndex::build(&tree, |tag| {
tag_items
.get(tag)
.map(|v| v.iter().map(String::as_str).collect())
.unwrap_or_default()
});
let build = t.elapsed();
let all = tree
.by_trigger
.get("minecraft:inventory_changed")
.map_or(0, Vec::len);
let held = [
"minecraft:iron_ingot",
"minecraft:oak_log",
"minecraft:cobblestone",
"minecraft:diamond_pickaxe",
"minecraft:bread",
"minecraft:torch",
"minecraft:oak_planks",
"minecraft:stick",
"minecraft:coal",
];
let t = std::time::Instant::now();
let mut candidates = 0;
for _ in 0..1000 {
candidates = index.candidates(held).len();
}
let per_change = t.elapsed() / 1000;
let recipes = tree
.by_trigger
.get("minecraft:recipe_unlocked")
.map_or(0, Vec::len);
let per_recipe = tree.recipe_criteria("minecraft:iron_pickaxe").len();
eprintln!(
"tree {load:?}; inventory_changed: {all} criteria, index built in {build:?}, \
a 9-stack inventory tests {candidates} (looked up in {per_change:?}); \
recipe_unlocked: {recipes} criteria, iron_pickaxe tests {per_recipe}"
);
assert!(candidates < all / 10);
}
struct Flat;
impl World for Flat {
fn dimension(&self) -> &str {
@@ -1090,6 +1264,94 @@ mod tests {
stack.id = "minecraft:tnt".into();
}
}
/// Only the criteria the held items could pass are tested; those that
/// need no particular item always are.
#[test]
fn inventory_index_keeps_the_criteria_the_items_could_pass() {
let criteria = [
serde_json::json!({"items": [{"items": "minecraft:diamond"}]}),
serde_json::json!({"items": [{"items": "#minecraft:planks"}]}),
serde_json::json!({"items": [{"count": {"min": 2}}]}),
serde_json::json!({"items": [{"count": 1}, {"items": ["minecraft:stick", "minecraft:apple"]}]}),
serde_json::json!({"slots": {"empty": 0}}),
serde_json::json!({"items": [{"items": "#minecraft:no_such_tag"}]}),
];
let mut tree = Tree::default();
for (i, conditions) in criteria.into_iter().enumerate() {
tree.list.push(Advancement {
id: format!("test:{i}"),
parent: None,
display: None,
criteria: vec![Criterion {
name: "c".into(),
trigger: "minecraft:inventory_changed".into(),
conditions,
}],
requirements: vec![vec!["c".into()]],
rewards: Rewards::default(),
});
tree.by_trigger
.entry("minecraft:inventory_changed".into())
.or_default()
.push((i, 0));
}
let index = InventoryIndex::build(&tree, |tag| match tag {
"minecraft:planks" => vec!["minecraft:oak_planks", "minecraft:birch_planks"],
_ => Vec::new(),
});
let found = |held: &[&str]| -> Vec<usize> {
index
.candidates(held.iter().copied())
.into_iter()
.map(|(ai, _)| ai)
.collect()
};
assert_eq!(found(&[]), [2, 4]);
assert_eq!(found(&["minecraft:dirt"]), [2, 4]);
assert_eq!(
found(&["minecraft:oak_planks", "minecraft:diamond"]),
[0, 1, 2, 4]
);
assert_eq!(found(&["minecraft:apple", "minecraft:apple"]), [2, 3, 4]);
}
/// A recipe unlocked tests only the criteria that name it.
#[test]
fn recipe_index_keeps_the_criteria_of_the_recipe() {
let mut tree = Tree::default();
for (i, conditions) in [
serde_json::json!({"recipes": "minecraft:oak_planks"}),
serde_json::json!({"recipes": "minecraft:stick"}),
serde_json::json!({}),
serde_json::json!({"recipes": "minecraft:oak_planks"}),
]
.into_iter()
.enumerate()
{
tree.list.push(Advancement {
id: format!("test:{i}"),
parent: None,
display: None,
criteria: vec![Criterion {
name: "c".into(),
trigger: "minecraft:recipe_unlocked".into(),
conditions,
}],
requirements: vec![vec!["c".into()]],
rewards: Rewards::default(),
});
tree.by_trigger
.entry("minecraft:recipe_unlocked".into())
.or_default()
.push((i, 0));
}
tree.index_recipes();
assert_eq!(
tree.recipe_criteria("minecraft:oak_planks"),
[(0, 0), (2, 0), (3, 0)]
);
assert_eq!(tree.recipe_criteria("minecraft:stick"), [(1, 0), (2, 0)]);
assert_eq!(tree.recipe_criteria("minecraft:torch"), [(2, 0)]);
}
#[test]
fn bucket_axolotl_block_advancements_require_the_placed_block() {
let ctx = Entities {
+25
View File
@@ -61,6 +61,8 @@ enum Animate {
Fire,
/// An active sculk sensor.
SculkSensor,
/// Potent sulfur that is not dry.
PotentSulfur,
}
fn step(facing: &str) -> [i32; 3] {
match facing {
@@ -128,6 +130,9 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
}
}
"respawn_anchor" if prop("charges").is_some_and(|c| c != "0") => Animate::RespawnAnchor,
"potent_sulfur" if prop("potent_sulfur_state").is_some_and(|s| s != "dry") => {
Animate::PotentSulfur
}
"bubble_column" => Animate::BubbleColumn {
drag: prop("drag").as_deref() == Some("true"),
},
@@ -819,6 +824,26 @@ fn block_animate_tick(
}
}
}
Animate::PotentSulfur => {
// PotentSulfurBlock.animateTick: under a water source, two
// bubbles and, one time in ten, the noxious gas.
let above = ctx.facts.get(ctx.state([pos[0], pos[1] + 1, pos[2]]));
if above.fluid == Fluid::Water && above.fluid_level == 8 && !above.fluid_falling {
for _ in 0..2 {
let r = engine.random();
let p = [
fx + f64::from(r.next_float()),
fy + 1.0 + f64::from(r.next_float()),
fz + f64::from(r.next_float()),
];
add(engine, T::SulfurBubbles, p, [0.0; 3]);
}
if next_int(engine.random(), 10) == 0 {
let name = "minecraft:block.potent_sulfur.noxious_gas";
sound(engine, name, [fx, fy, fz], 1.0, 1.0);
}
}
}
Animate::Mycelium => {
let r = engine.random();
if next_int(r, 10) == 0 {
+137 -21
View File
@@ -2,7 +2,7 @@
//! small mixer standing in for OpenAL: one channel per source with its gain,
//! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0,
//! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding
//! (streams on a worker thread) and stereo panning.
//! (streams on a worker thread) and OpenAL Soft's stereo panning.
use crate::Result;
use crate::sound_engine::{
Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance,
@@ -45,6 +45,7 @@ struct Mixer {
channels: HashMap<ChannelId, Channel>,
listener: [f64; 3],
listener_yaw: f32,
listener_pitch: f32,
limiter_peak: f32,
}
/// A sound the player could have heard (`SoundEventListener.onPlaySound`):
@@ -157,6 +158,9 @@ pub struct Audio {
/// Positional sounds played since the last drain, kept while the world
/// is open to the network so guests hear them too.
pub capture: Option<Vec<(String, [f64; 3], f32, f32)>>,
/// How many times each positional sound played (the control socket's `status`),
/// with or without an audio device.
pub heard: std::collections::BTreeMap<String, u32>,
}
fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
use symphonia::core::{
@@ -331,6 +335,32 @@ impl Backend for MixerBackend {
.unwrap_or(true)
}
}
/// OpenAL Soft's stereo gains `[left, right]` for a mono source in a
/// direction given in listener space (right, up, forward; any length).
/// Vanilla's context (`Library.createAttributes`: HRTF off) on a stereo
/// output renders pairwise: front azimuths are stretched by 1.5
/// (`ScaleAzimuthFront`, so 60 degrees off-centre pans fully) and the
/// direction is decoded by the first-order stereo decoder, 0.5 W, 0.5 Y and
/// 0.0957 X in this scaling. A centred source gets 0.596 on each side, one
/// behind 0.404, one above or below 0.5, one at the source's own position
/// is panned to the front. Matches OpenAL Soft 1.25.2 (LWJGL 3.4.3, the
/// pinned client's) rendered through `ALC_SOFT_loopback` within 1e-5.
fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] {
let length = (right * right + up * up + forward * forward).sqrt();
if length <= f32::EPSILON {
return stereo_gains(0.0, 0.0, 1.0);
}
let elevation = (up / length).clamp(-1.0, 1.0).asin();
let mut azimuth = right.atan2(forward);
if azimuth.abs() < std::f32::consts::FRAC_PI_2 {
azimuth = (azimuth.abs() * 1.5)
.min(std::f32::consts::FRAC_PI_2)
.copysign(azimuth);
}
let side = azimuth.sin() * elevation.cos();
let front = azimuth.cos() * elevation.cos() * 0.095_660_8;
[0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front]
}
/// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference
/// distance 0 and rolloff 1: the distance clamps to the max distance).
fn distance_gain(linear: Option<f32>, distance: f32) -> f32 {
@@ -345,9 +375,30 @@ fn distance_gain(linear: Option<f32>, distance: f32) -> f32 {
fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
data.fill(0.0);
let listener = mixer.listener;
let yaw = mixer.listener_yaw.to_radians();
// The camera's forward and up vectors (`Camera.forwardVector`/`upVector`)
// and OpenAL's right = forward x up.
let (yaw, pitch) = (
f64::from(mixer.listener_yaw.to_radians()),
f64::from(mixer.listener_pitch.to_radians()),
);
let forward = [
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
];
let up = [
-yaw.sin() * pitch.sin(),
pitch.cos(),
yaw.cos() * pitch.sin(),
];
let right = [
forward[1] * up[2] - forward[2] * up[1],
forward[2] * up[0] - forward[0] * up[2],
forward[0] * up[1] - forward[1] * up[0],
];
let dot = |a: [f64; 3], b: [f64; 3]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) as f32;
// Gains and pans per source for this buffer.
let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new();
let mut voices: Vec<(ChannelId, [f32; 3], f64)> = Vec::new();
for (id, c) in &mixer.channels {
let Some((_, source_rate)) = &c.samples else {
continue;
@@ -366,19 +417,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
};
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance);
// The listener's right vector for a Minecraft yaw.
let side = if c.relative {
(d[0] as f32) / distance.max(0.001)
// Relative sources are already in OpenAL's listener space (-Z ahead).
let [left, right] = if c.relative {
stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32)
} else {
(-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001)
};
let pan = side.clamp(-1.0, 1.0);
let left = gain * (1.0 - pan.max(0.0) * 0.6);
let right = gain * (1.0 + pan.min(0.0) * 0.6);
stereo_gains(dot(d, right), dot(d, up), dot(d, forward))
}
.map(|pan| gain * pan);
let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0));
voices.push((*id, left, right, step));
voices.push((*id, [left, right, gain], step));
}
for (id, left, right, step) in voices {
for (id, [left, right, gain], step) in voices {
let Some(c) = mixer.channels.get_mut(&id) else {
continue;
};
@@ -402,16 +451,19 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
frame[0] += s * left;
frame[1] += s * right;
} else {
frame[0] += s * (left + right) / 2.0;
// A mono output has no panning: the source's own gain.
frame[0] += s * gain;
}
c.position += step;
}
}
// Limit the whole buffer together, preserving waveform and stereo balance
// instead of flattening each overloaded sample; release over 50 ms.
// instead of flattening each overloaded sample; release over 200 ms
// (OpenAL Soft's output limiter, `ALC_OUTPUT_LIMITER_SOFT`, releases
// over 0.2 s).
let peak = data.iter().fold(1.0f32, |peak, s| peak.max(s.abs()));
mixer.limiter_peak = mixer.limiter_peak.max(peak);
let release = (-1.0 / (0.05 * rate as f32)).exp();
let release = (-1.0 / (0.2 * rate as f32)).exp();
for frame in data.chunks_mut(channels) {
let gain = mixer.limiter_peak.recip();
for s in frame {
@@ -542,6 +594,7 @@ impl Audio {
random: LegacyRandom::new(crate::sound_engine::unique_seed()),
source_override: None,
capture: None,
heard: Default::default(),
}
}
#[cfg(not(feature = "audio"))]
@@ -591,13 +644,15 @@ impl Audio {
backend: &mut self.backend,
}
}
/// `SoundManager.updateSource`: the camera position and yaw.
pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) {
/// `SoundManager.updateSource`: the camera position and rotation
/// (`Listener.setTransform` takes its forward and up vectors).
pub fn set_listener(&mut self, position: [f64; 3], yaw: f32, pitch: f32) {
self.listener = position;
self.listener_yaw = yaw;
if let Ok(mut m) = self.backend.mixer.lock() {
m.listener = position;
m.listener_yaw = yaw;
m.listener_pitch = pitch;
}
}
/// Sync the volume options, refreshing the categories that changed
@@ -682,6 +737,9 @@ impl Audio {
if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) {
capture.push((event.to_owned(), at, volume, pitch));
}
if at.is_some() {
*self.heard.entry(event.to_owned()).or_default() += 1;
}
self.sync_volumes();
let event = crate::sound_events::normalize(event);
let source = self
@@ -908,8 +966,9 @@ mod tests {
}
let mut data = [0.0; 16];
mix(&mut m, &mut data, 2, 48_000);
// West of a listener facing south: fully on the right.
for (frame, sample) in data.as_chunks::<2>().0.iter().zip(wave) {
assert!((frame[0] - sample * 0.4).abs() < 1e-6, "{frame:?}");
assert!(frame[0].abs() < 1e-6, "{frame:?}");
assert!((frame[1] - sample).abs() < 1e-6, "{frame:?}");
}
assert!(data.iter().all(|s| s.abs() <= 1.0));
@@ -920,9 +979,10 @@ mod tests {
let mut m = Mixer::default();
m.channels
.insert(1, channel(vec![0.25; 2], None, [0.0; 3], true));
let quiet = 0.25 * stereo_gains(0.0, 0.0, 1.0)[0];
let mut data = [0.0; 16];
mix(&mut m, &mut data, 2, 48_000);
assert_eq!(data, [0.25; 16]);
assert_eq!(data, [quiet; 16]);
for id in 2..=5 {
m.channels
@@ -935,7 +995,7 @@ mod tests {
mix(&mut m, &mut recovery, 2, 48_000);
assert!(recovery[0] > 0.0 && recovery[0] < 0.1);
assert!(recovery.windows(2).all(|w| w[1] >= w[0]));
assert_eq!(*recovery.last().unwrap(), 0.25);
assert_eq!(*recovery.last().unwrap(), quiet);
}
#[test]
@@ -953,4 +1013,60 @@ mod tests {
let first = data[0] + data[1];
assert!(first > 1.4 && first < 3.1, "{first}");
}
#[test]
fn stereo_panning_matches_openal_soft() {
// OpenAL Soft 1.25.2 (LWJGL 3.4.3's macOS build), stereo loopback
// device with vanilla's attributes, 1 kHz sine 4 blocks away.
let cases = [
((0.0, 0.0, 1.0), [0.5957, 0.5957]),
((-1.0, 0.0, 0.0), [1.0, 0.0]),
((1.0, 0.0, 0.0), [0.0, 1.0]),
((0.0, 0.0, -1.0), [0.4043, 0.4043]),
((0.0, 1.0, 0.0), [0.5, 0.5]),
((0.0, -1.0, 0.0), [0.5, 0.5]),
((-1.0, 0.0, 1.0), [0.9985, 0.0747]),
((-1.0, 0.0, -1.0), [0.7859, 0.0788]),
((0.0, 0.0, 0.0), [0.5957, 0.5957]),
];
for ((right, up, forward), expected) in cases {
let gains = stereo_gains(right, up, forward);
for (g, e) in gains.into_iter().zip(expected) {
assert!((g - e).abs() < 1e-4, "{right} {up} {forward}: {gains:?}");
}
}
}
#[test]
fn panning_follows_the_camera_rotation() {
let gains = |yaw: f32, pitch: f32, at: [f32; 3]| {
let mut m = Mixer {
listener_yaw: yaw,
listener_pitch: pitch,
..Mixer::default()
};
m.channels.insert(1, channel(vec![1.0; 4], None, at, true));
let mut data = [0.0; 2];
mix(&mut m, &mut data, 2, 48_000);
data
};
let close =
|a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4;
// Facing south (yaw 0), east is on the left; facing north, on the right.
assert!(close(gains(0.0, 0.0, [1.0, 0.0, 0.0]), [1.0, 0.0]));
assert!(close(gains(180.0, 0.0, [1.0, 0.0, 0.0]), [0.0, 1.0]));
// Looking straight down, a source below is ahead and one south is above.
assert!(close(gains(0.0, 90.0, [0.0, -1.0, 0.0]), [0.5957, 0.5957]));
assert!(close(gains(0.0, 90.0, [0.0, 0.0, 1.0]), [0.5, 0.5]));
}
#[test]
fn a_mono_output_plays_sources_unpanned() {
let mut m = Mixer::default();
m.channels
.insert(1, channel(vec![0.5; 4], None, [0.0, 0.0, -3.0], true));
let mut data = [0.0; 2];
mix(&mut m, &mut data, 1, 48_000);
assert_eq!(data, [0.5; 2]);
}
}
+1 -1
View File
@@ -174,7 +174,7 @@ pub fn discovery_url() -> String {
fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.timeout(Duration::from_secs(15))
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
.user_agent(&format!("Horizon/{}", horizon_core::release::VERSION))
.build()
}
@@ -130,7 +130,7 @@ impl Session {
"initialize" => Ok(json!({
"protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL),
"capabilities": { "tools": {} },
"serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") },
"serverInfo": { "name": "horizon-ctl", "version": horizon_core::release::VERSION },
"instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).",
})),
"ping" => Ok(json!({})),
@@ -939,7 +939,14 @@ impl BlockEntityRenderer {
!matches!(self.kind(state), Kind::None)
}
/// ChestRenderer and BannerRenderer submit their animated models for crumbling.
pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec<Vertex>) {
pub fn render_breaking(
&self,
scene: &Scene,
pos: [i32; 3],
state: u32,
stage: [f32; 2],
out: &mut Vec<Vertex>,
) {
if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) {
return;
}
@@ -958,7 +965,7 @@ impl BlockEntityRenderer {
false,
out,
);
crate::breaking::entity_geometry(&mut out[start..], origin);
crate::breaking::entity_geometry(&mut out[start..], origin, stage);
}
/// `ChestRenderer.extractRenderState`'s openness for the chest of `state`
/// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`)
@@ -1942,7 +1949,7 @@ mod tests {
let mut base = Vec::new();
renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base);
let mut cracks = Vec::new();
renderer.render_breaking(&scene, [0; 3], state, &mut cracks);
renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut cracks);
assert!(!cracks.is_empty());
assert_eq!(
base.iter().map(|v| v.pos).collect::<Vec<_>>(),
@@ -1956,7 +1963,7 @@ mod tests {
scene.lid = &|_| 1.0;
}
let mut animated = Vec::new();
renderer.render_breaking(&scene, [0; 3], state, &mut animated);
renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut animated);
assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos));
scene.game_time = 0;
scene.lid = &|_| 0.0;
+47 -9
View File
@@ -23,7 +23,21 @@ pub fn decal_uv([x, y, z]: [f32; 3], direction: Direction) -> [f32; 2] {
[-p[0], -p[1]]
}
pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: &mut Vec<Vertex>) {
/// The light bytes of a crack vertex: the pass is unlit, so they carry the origin of the
/// vertex's destroy stage sprite (each crack in `LevelRenderer.destroyingBlocks` has its own
/// stage; every stage sprite has the same size, `crumbling_sprite.zw`).
pub fn stage_light([u0, v0]: [f32; 2]) -> u32 {
let q = |x: f32| (x.clamp(0.0, 1.0) * 65535.0).round() as u32;
q(u0) | (q(v0) << 16)
}
pub fn geometry(
model: &BakedModel,
origin: glam::Vec3,
translucent: bool,
stage: [f32; 2],
out: &mut Vec<Vertex>,
) {
// Vanilla visits all six cull groups and then the unculled faces, even beside solid neighbours.
for cull in Direction::ALL.map(Some).into_iter().chain([None]) {
for face in model.faces.iter().filter(|face| face.quad.cull == cull) {
@@ -33,7 +47,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out:
uv: decal_uv(pos, face.quad.facing),
layer: if translucent { 12 } else { 11 },
color: 0xffff_ffff,
light: 240 | (240 << 8),
light: stage_light(stage),
normal: [0; 4],
});
}
@@ -42,7 +56,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out:
}
/// Project a block entity's transformed quads onto the same destroy-stage pass.
pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) {
pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3, stage: [f32; 2]) {
for quad in vertices.as_chunks_mut::<4>().0 {
let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos));
let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]);
@@ -65,7 +79,7 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) {
vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing);
vertex.layer = 11;
vertex.color = 0xffff_ffff;
vertex.light = 240 | (240 << 8);
vertex.light = stage_light(stage);
}
}
}
@@ -73,6 +87,24 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stage_origin_survives_the_light_bytes() {
// entity.wgsl's `wrap`: the low and high 16 bits over 65535.
for origin in [[0.0, 0.0], [0.5, 0.25], [0.123_456, 0.987_654], [1.0, 1.0]] {
let light = stage_light(origin);
let back = [
(light & 0xffff) as f32 / 65535.0,
(light >> 16) as f32 / 65535.0,
];
for k in 0..2 {
assert!(
(back[k] - origin[k]).abs() <= 0.5 / 65535.0,
"{origin:?} -> {back:?}"
);
}
}
}
use crate::models::catalog::BakedFace;
use horizon_assets::{bake::ModelQuad, model::Material};
fn slab_top() -> BakedModel {
@@ -109,7 +141,13 @@ mod tests {
fn slab_overlay_follows_baked_top_not_unit_cube() {
let model = slab_top();
let mut vertices = Vec::new();
geometry(&model, glam::Vec3::new(2.0, 3.0, 4.0), false, &mut vertices);
geometry(
&model,
glam::Vec3::new(2.0, 3.0, 4.0),
false,
[0.0; 2],
&mut vertices,
);
assert_eq!(vertices.len(), 4);
for (v, p) in vertices.iter().zip(model.faces[0].quad.positions) {
assert_eq!(v.pos, [p[0] + 2.0, p[1] + 3.0, p[2] + 4.0]);
@@ -120,14 +158,14 @@ mod tests {
fn entity_overlay_uses_block_local_projected_uvs() {
let origin = glam::Vec3::new(12.0, -3.0, 8.0);
let mut expected = Vec::new();
geometry(&slab_top(), origin, false, &mut expected);
geometry(&slab_top(), origin, false, [0.0; 2], &mut expected);
let mut actual = expected.clone();
for vertex in &mut actual {
vertex.uv = [0.0; 2];
vertex.layer = 0;
vertex.color = 0;
}
entity_geometry(&mut actual, origin);
entity_geometry(&mut actual, origin, [0.0; 2]);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&actual),
bytemuck::cast_slice::<_, u8>(&expected)
@@ -143,7 +181,7 @@ mod tests {
#[test]
fn translucent_overlay_has_its_own_pass() {
let mut vertices = Vec::new();
geometry(&slab_top(), glam::Vec3::ZERO, true, &mut vertices);
geometry(&slab_top(), glam::Vec3::ZERO, true, [0.0; 2], &mut vertices);
assert!(vertices.iter().all(|v| v.layer == 12));
}
#[test]
@@ -151,7 +189,7 @@ mod tests {
let mut model = slab_top();
model.faces.clear();
let mut vertices = Vec::new();
geometry(&model, glam::Vec3::ZERO, false, &mut vertices);
geometry(&model, glam::Vec3::ZERO, false, [0.0; 2], &mut vertices);
assert!(vertices.is_empty());
}
}
+26 -3
View File
@@ -15,8 +15,9 @@ use horizon_world::{
entity_obstruction::EntityIdentity,
fluid::{FluidKind, FluidState},
liquid_collision::LiquidCollisionWorld,
piston_shape::PistonCollisionWorld,
powder_snow_collision::{PowderSnowEntity, PowderSnowWorld},
registry::{BlockRegistry, BlockTableFile},
registry::{BlockRegistry, BlockStateId, BlockTableFile},
world_movement::{
CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision,
resolve_world_movement,
@@ -259,8 +260,30 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> {
fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result<Option<bool>> {
Ok(None)
}
fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result<Option<VoxelShape>> {
Ok(None)
/// `MovingPistonBlock.getCollisionShape`: the block entity's moving shape
/// (`PistonMovingBlockEntity.getCollisionShape`), outside any push.
fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result<Option<VoxelShape>> {
let Some(&(_, piston)) = self.world.moving_pistons.iter().find(|(q, _)| *q == p) else {
return Ok(None);
};
let binding = self.binding;
let Some(pistons) = binding.pistons() else {
return Ok(None);
};
pistons
.collision_shape(self, p, piston, None)
.map(Some)
.map_err(io::Error::other)
}
}
impl PistonCollisionWorld for SceneCollisions<'_, '_> {
type Error = io::Error;
/// `BlockState.getCollisionShape(level, pos)` of the moved state.
fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result<VoxelShape> {
let binding = self.binding;
binding
.collision_shape(self, state, p)
.map_err(io::Error::other)
}
}
impl DynamicCollisionWorld for SceneCollisions<'_, '_> {
+1 -1
View File
@@ -528,7 +528,7 @@ impl Furnace {
let has_fuel = self.items[1].is_some();
if lit || has_fuel && has_ingredient {
if let Some(ingredient) = self.items[0].clone() {
if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient).cloned() {
if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient) {
if self.cooking_timer == 0 {
self.cooking_total = total_time(recipe.time, self.speed);
}
+96
View File
@@ -1102,7 +1102,11 @@ pub struct Recipes {
facts: HashMap<Arc<str>, Facts>,
/// The `#minecraft:curse` enchantments.
curses: HashSet<String>,
/// The first cooking recipe of each kind taking each item, built at the
/// first lookup (furnaces look theirs up every tick).
cook_index: std::sync::OnceLock<CookIndex>,
}
type CookIndex = HashMap<String, crate::fast_hash::FxHashMap<String, usize>>;
/// `MinMaxBounds.Ints` as (min, max) with the given defaults.
fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) {
match v {
@@ -1421,6 +1425,7 @@ impl Recipes {
meta,
facts,
curses,
cook_index: Default::default(),
})
}
/// Match a `size`x`size` grid (row-major) against the crafting recipes.
@@ -1606,6 +1611,22 @@ impl Recipes {
out
}
pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
let index = self.cook_index.get_or_init(|| {
let mut index = CookIndex::new();
for (i, c) in self.cooking.iter().enumerate() {
let of_kind = index.entry(c.kind.clone()).or_default();
for item in &c.ingredient.0 {
of_kind.entry(item.clone()).or_insert(i);
}
}
index
});
let i = *index.get(kind)?.get(&*input.item)?;
self.cooking.get(i)
}
/// `cook` by scanning every recipe, as it was before the index.
#[cfg(test)]
fn cook_scan(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
self.cooking
.iter()
.find(|c| c.kind == kind && c.ingredient.test(input))
@@ -1625,6 +1646,80 @@ mod tests {
s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")];
s
}
/// About vanilla's count of cooking recipes: four kinds, ingredients of
/// one to twelve items, overlapping (several recipes take some items).
fn cooking_book() -> Recipes {
let kinds = ["smelting", "blasting", "smoking", "campfire_cooking"];
let cooking = (0..320usize)
.map(|i| Cooking {
id: format!("r{i}"),
category: "misc".into(),
group: String::new(),
kind: kinds[i % 4].into(),
ingredient: ingredient(
&(0..1 + i % 12)
.map(|k| format!("minecraft:item_{}", (i * 7 + k * 13) % 400))
.collect::<Vec<_>>()
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
),
result: ItemStack::new("minecraft:stone", 1),
experience: 0.1,
time: 200,
})
.collect();
Recipes {
crafting: Vec::new(),
cooking,
meta: HashMap::new(),
facts: HashMap::new(),
curses: HashSet::new(),
cook_index: Default::default(),
}
}
#[test]
fn cook_finds_the_first_recipe_the_scan_finds() {
let recipes = cooking_book();
for kind in [
"smelting",
"blasting",
"smoking",
"campfire_cooking",
"other",
] {
for n in 0..420 {
let stack = ItemStack::new(&format!("minecraft:item_{n}"), 1);
let a = recipes.cook(kind, &stack).map(|c| &c.id);
let b = recipes.cook_scan(kind, &stack).map(|c| &c.id);
assert_eq!(a, b, "{kind} item_{n}");
}
}
}
/// A furnace's recipe lookup, once per lit furnace per tick.
#[test]
#[ignore]
fn cook_cost() {
let recipes = cooking_book();
let stacks: Vec<ItemStack> = (0..1000)
.map(|n| ItemStack::new(&format!("minecraft:item_{}", n % 400), 1))
.collect();
let t = std::time::Instant::now();
let a = stacks
.iter()
.filter(|s| recipes.cook_scan("smelting", s).cloned().is_some())
.count();
let before = t.elapsed().as_secs_f64() * 1e3;
recipes.cook("smelting", &stacks[0]);
let t = std::time::Instant::now();
let b = stacks
.iter()
.filter(|s| recipes.cook("smelting", s).is_some())
.count();
let after = t.elapsed().as_secs_f64() * 1e3;
assert_eq!(a, b);
println!("1000 furnace lookups (scan and clone -> index): {before:.3} ms -> {after:.3} ms");
}
fn run(special: &Special, cells: &[ItemStack]) -> Option<ItemStack> {
let recipes = Recipes {
crafting: Vec::new(),
@@ -1632,6 +1727,7 @@ mod tests {
meta: HashMap::new(),
facts: HashMap::new(),
curses: HashSet::new(),
cook_index: Default::default(),
};
let ctx = Context {
recipes: &recipes,
+23 -6
View File
@@ -105,18 +105,23 @@ impl Report {
}
}
/// The release tag (the launcher installs each build in a folder named after it) and the client's
/// own version, or just the latter.
/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's
/// crate version; for a build from source, that version alone.
pub fn version() -> String {
let version = env!("CARGO_PKG_VERSION");
match release_tag() {
Some(tag) => format!("{tag} (client {version})"),
None => version.to_owned(),
match (horizon_core::release::RELEASE, release_tag()) {
(Some(_), Some(tag)) => tag,
(None, Some(tag)) => format!("{tag} (client {version})"),
(_, None) => version.to_owned(),
}
}
/// The release this binary came with: launcher installs live in a folder named after the tag.
/// The release this binary came with: the version release.yml built in (docs/versioning.md), else
/// the folder the launcher installed it in, named after the tag (releases from before 0.2).
pub fn release_tag() -> Option<String> {
if let Some(version) = horizon_core::release::RELEASE {
return Some(format!("v{version}"));
}
let exe = std::env::current_exe().ok()?;
let folder = exe.parent()?.file_name()?.to_str()?;
(folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit()))
@@ -517,6 +522,18 @@ pub fn debug_crash_after() -> Option<std::time::Duration> {
mod tests {
use super::*;
#[test]
fn a_release_reports_its_built_in_version() {
// release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed.
match horizon_core::release::RELEASE {
Some(version) => {
assert_eq!(release_tag(), Some(format!("v{version}")));
assert_eq!(super::version(), format!("v{version}"));
}
None => assert!(release_tag().is_none() || super::version().contains("(client ")),
}
}
fn report() -> Report {
Report {
time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(),
+1
View File
@@ -44,6 +44,7 @@ pub struct Creative {
search_index: Vec<SearchEntry>,
}
/// Display names from the pinned en_us language file.
#[derive(Default)]
pub struct Names {
map: HashMap<String, String>,
}
+133
View File
@@ -0,0 +1,133 @@
//! Horizon Extras' dynamic lights (docs/extras.md): a torch, lantern or other light source held by
//! a player or mob, dropped as an item, or an entity on fire lights the blocks and entities
//! around it. Not in vanilla; off by default.
//!
//! Client-only and at render time: the light engine, chunk meshes and saves never see it. Each
//! frame the game picks the [`MAX`] sources nearest the camera; terrain.wgsl and entity.wgsl
//! raise a vertex's block light to `level - distance` (one level per block, as block light falls
//! off) when that is brighter. Off, the list is empty and the shaders skip the loop.
use crate::blocks::BlockFacts;
use glam::DVec3;
use horizon_world::registry::BlockRegistry;
use std::collections::HashMap;
/// Lights the shaders read: `Globals.dynamic_lights` in gfx.rs, terrain.wgsl and entity.wgsl.
pub const MAX: usize = 16;
/// What an entity on fire gives off, as a lit campfire or fire block does.
pub const BURNING: u8 = 15;
/// Sources farther than this from the camera light nothing it can see well.
const REACH: f64 = 96.0;
/// How brightly each item glows when held or dropped.
#[derive(Debug, Default)]
pub struct Luminance(HashMap<String, u8>);
impl Luminance {
/// A block item glows like its block's default state (`getLightEmission`): torches 14,
/// lanterns and glowstone 15, a lit redstone torch 7; a furnace's item, unlit, not at all.
pub fn new(facts: &BlockFacts, registry: &BlockRegistry) -> Self {
let mut map = HashMap::new();
for (id, state) in facts.states.iter().enumerate() {
if state.emission == 0 || *state.item != *state.name {
continue;
}
if registry.default_state(&state.name).map(|d| d.0 as usize) == Some(id) {
map.insert(state.item.to_string(), state.emission);
}
}
// A bucket of lava glows as lava does.
map.insert("minecraft:lava_bucket".into(), 15);
Self(map)
}
pub fn of(&self, item: &str) -> u8 {
self.0.get(item).copied().unwrap_or(0)
}
#[cfg(test)]
fn from_pairs(pairs: &[(&str, u8)]) -> Self {
Self(pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect())
}
}
/// One light this frame: where it is (world space) and its level, 1 to 15.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Source {
pub at: DVec3,
pub level: u8,
}
/// The [`MAX`] sources nearest `camera` within reach, as the shaders read them: camera-relative
/// position and level. Overwrites `out`.
pub fn select(sources: &[Source], camera: DVec3, out: &mut Vec<[f32; 4]>) {
out.clear();
let key = |s: &Source| s.at.distance_squared(camera);
let mut near: Vec<&Source> = sources
.iter()
.filter(|s| s.level > 0 && key(s) <= REACH * REACH)
.collect();
near.sort_by(|a, b| key(a).total_cmp(&key(b)));
out.extend(near.into_iter().take(MAX).map(|s| {
let p = (s.at - camera).as_vec3();
[p.x, p.y, p.z, f32::from(s.level.min(15))]
}));
}
/// The block light a vertex at `pos` (camera-relative) gets from `lights`, 0 to 15: the WGSL
/// `dynamic_block_light` in Rust, for tests.
pub fn level_at(pos: [f32; 3], lights: &[[f32; 4]]) -> f32 {
lights.iter().fold(0.0f32, |level, l| {
let d =
((pos[0] - l[0]).powi(2) + (pos[1] - l[1]).powi(2) + (pos[2] - l[2]).powi(2)).sqrt();
level.max(l[3] - d)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nearest_sources_win() {
let camera = DVec3::new(100.0, 64.0, 100.0);
let mut sources: Vec<Source> = (0..40)
.map(|i| Source {
at: camera + DVec3::new(f64::from(i), 0.0, 0.0),
level: 14,
})
.collect();
sources.push(Source {
at: camera + DVec3::new(0.5, 0.0, 0.0),
level: 0,
});
sources.push(Source {
at: camera + DVec3::new(0.0, 0.0, 200.0),
level: 15,
});
let mut out = Vec::new();
select(&sources, camera, &mut out);
assert_eq!(out.len(), MAX);
assert_eq!(out[0], [0.0, 0.0, 0.0, 14.0]);
assert_eq!(out[MAX - 1][0], (MAX - 1) as f32);
select(&[], camera, &mut out);
assert!(out.is_empty());
}
#[test]
fn light_falls_off_a_level_per_block() {
let torch = [[0.0, 0.0, 0.0, 14.0]];
assert_eq!(level_at([0.0, 0.0, 0.0], &torch), 14.0);
assert_eq!(level_at([3.0, 4.0, 0.0], &torch), 9.0);
assert_eq!(level_at([20.0, 0.0, 0.0], &torch), 0.0);
let two = [[0.0, 0.0, 0.0, 14.0], [10.0, 0.0, 0.0, 15.0]];
assert_eq!(level_at([8.0, 0.0, 0.0], &two), 13.0);
assert_eq!(level_at([0.0; 3], &[]), 0.0);
}
#[test]
fn item_luminance() {
let l = Luminance::from_pairs(&[("minecraft:torch", 14)]);
assert_eq!(l.of("minecraft:torch"), 14);
assert_eq!(l.of("minecraft:stone"), 0);
}
}
+1
View File
@@ -60,6 +60,7 @@ pub struct ItemProps {
/// `minecraft:brewing_fuel` present.
pub brewing_fuel: bool,
}
#[derive(Default)]
pub struct Enchantments {
pub list: Vec<Enchantment>,
index: HashMap<Arc<str>, usize>,
+25 -4
View File
@@ -14,11 +14,13 @@ struct Globals {
// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
end_portal_sprites: array<vec4<f32>, 2>,
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
// y: Nether cardinal lighting.
// y: Nether cardinal lighting, z: how many dynamic_lights are set.
time: vec4<f32>,
crumbling_sprite: vec4<f32>,
// Selection outline parameters (read by terrain.wgsl).
outline_params: vec4<f32>,
// Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs).
dynamic_lights: array<vec4<f32>, 16>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@@ -58,20 +60,33 @@ 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);
}
// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units
// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one
// level less per block. time.z of them are set: none when the extra is off, so no loop runs.
fn dynamic_block_light(pos: vec3<f32>) -> f32 {
let count = min(u32(globals.time.z), 16u);
var level = 0.0;
for (var i = 0u; i < count; i++) {
let l = globals.dynamic_lights[i];
level = max(level, l.w - distance(pos, l.xyz));
}
return level * 16.0;
}
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);
out.uv = uv;
let l = vec2(f32(light.y), f32(light.x));
let l = vec2(max(f32(light.y), dynamic_block_light(position)), f32(light.x));
let lm = textureSampleLevel(lightmap, lightmap_sampler,
clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
// Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit.
let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u
|| overlay == 11u || overlay == 12u;
out.light_color = select(lm, vec4(1.0), unlit);
// Overlay 6 (beacon beams): the light bytes carry the sprite's v range.
// Overlay 6 (beacon beams): the light bytes carry the sprite's v range; 11 and 12
// (cracks): the destroy stage sprite's origin.
out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0;
// minecraft_mix_light: the vertex colour times the cardinal light only.
var c = color;
@@ -147,7 +162,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
var uv = in.uv;
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
if in.overlay == 11u || in.overlay == 12u {
uv = globals.crumbling_sprite.xy + fract(in.uv) * globals.crumbling_sprite.zw;
// Each crack's stage sprite origin comes in its light bytes (breaking::stage_light).
uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw;
}
var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front);
if in.overlay == 9u || in.overlay == 10u {
@@ -188,3 +204,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
return color;
}
// RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off).
@fragment fn fs_water_mask() -> @location(0) vec4<f32> {
return vec4(0.0);
}
+69
View File
@@ -918,6 +918,43 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemE
})
}
/// `OminousItemSpawner.addAdditionalSaveData`: its item (left out when
/// empty) and `spawn_item_after_ticks`. Its tick count is the entity's
/// `tickCount`, which isn't saved: a reloaded spawner counts from 0 again.
pub fn ominous_item_spawner_to_nbt(
item: &crate::items::ItemStack,
position: Vec3,
spawn_item_after: i64,
uuid: [i32; 4],
raw: Option<&Tag>,
) -> Tag {
let base = Base {
id: "minecraft:ominous_item_spawner",
uuid,
position,
motion: Vec3::ZERO,
rotation: [0.0, 0.0],
on_ground: false,
fall_distance: 0.0,
};
let mut tag = base.tag(raw);
put(&mut tag, "item", item_to_nbt(item));
put(
&mut tag,
"spawn_item_after_ticks",
Tag::Long(spawn_item_after),
);
tag
}
/// `OminousItemSpawner.readAdditionalSaveData`: the item, where it floats
/// and `spawn_item_after_ticks` (0 when absent). None without an item:
/// such a spawner would spawn nothing.
pub fn ominous_item_spawner_from_nbt(tag: &Tag) -> Option<(crate::items::ItemStack, Vec3, i64)> {
let item = tag.get("item").and_then(item_from_nbt)?;
let after = number(tag.get("spawn_item_after_ticks")).unwrap_or(0);
Some((item, position(tag)?, after))
}
/// `ExperienceOrb`: Health, Age, Value, Count.
pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
let base = Base {
@@ -1505,6 +1542,38 @@ mod tests {
use super::*;
use crate::items::ItemStack;
/// The item, the spawn delay and the fields Horizon doesn't model come
/// back; a compound without an item is no spawner.
#[test]
fn ominous_item_spawner_round_trip() {
let item = ItemStack {
item: Arc::from("minecraft:ominous_trial_key"),
count: 1,
damage: 0,
extra: None,
};
let raw = Tag::compound([("CustomName", string("kept"))]);
let at = Vec3::new(10.5, 64.25, -3.5);
let tag = ominous_item_spawner_to_nbt(&item, at, 97, [1, 2, 3, 4], Some(&raw));
assert_eq!(
kind(&tag).as_deref(),
Some("minecraft:ominous_item_spawner")
);
assert_eq!(uuid(&tag), Some([1, 2, 3, 4]));
assert!(matches!(
tag.get("spawn_item_after_ticks"),
Some(Tag::Long(97))
));
assert!(tag.get("CustomName").is_some());
let (back, pos, after) = ominous_item_spawner_from_nbt(&tag).unwrap();
assert_eq!(
(back.item.as_ref(), back.count),
("minecraft:ominous_trial_key", 1)
);
assert_eq!((pos, after), (at, 97));
assert!(ominous_item_spawner_from_nbt(&raw).is_none());
}
#[test]
fn falling_block_round_trip_keeps_impact_distance_and_settings() {
let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]);
+21 -4
View File
@@ -69,6 +69,8 @@ impl Corner {
#[derive(Clone, Debug, PartialEq)]
pub struct Extras {
pub fullbright: bool,
/// Held, dropped and burning light sources light their surroundings (`dynamic_light`).
pub dynamic_lights: bool,
pub zoom: bool,
/// A vanilla key name (`key.keyboard.z`).
pub zoom_key: String,
@@ -110,6 +112,7 @@ impl Default for Extras {
fn default() -> Self {
Self {
fullbright: false,
dynamic_lights: false,
zoom: false,
zoom_key: "key.keyboard.z".into(),
zoom_level: 4,
@@ -158,6 +161,7 @@ impl Extras {
};
match key.trim() {
"fullbright" => e.fullbright = flag(e.fullbright),
"dynamicLights" => e.dynamic_lights = flag(e.dynamic_lights),
"zoom" => e.zoom = flag(e.zoom),
"zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(),
"zoomLevel" => {
@@ -201,8 +205,9 @@ impl Extras {
}
pub fn serialize(&self) -> String {
format!(
"fullbright:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
bool_text(self.fullbright),
bool_text(self.dynamic_lights),
bool_text(self.zoom),
self.zoom_key,
self.zoom_level,
@@ -423,6 +428,7 @@ impl Cps {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Item {
Fullbright,
DynamicLights,
Zoom,
ZoomKey,
ZoomLevel,
@@ -452,6 +458,7 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
vec![
Err("Lighting"),
Ok(Fullbright),
Ok(DynamicLights),
Err("Zoom"),
Ok(Zoom),
Ok(ZoomKey),
@@ -501,6 +508,7 @@ impl Item {
pub fn caption(self) -> &'static str {
match self {
Item::Fullbright => "Fullbright",
Item::DynamicLights => "Dynamic lights",
Item::Zoom => "Zoom",
Item::ZoomKey => "Zoom key",
Item::ZoomLevel => "Starting zoom",
@@ -533,7 +541,8 @@ impl Item {
KeystrokesCorner | KeystrokesCps => Keystrokes,
MouseTweaksWheel => MouseTweaks,
SortKey => Sort,
Fullbright | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort | AutoReconnect => {
Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort
| AutoReconnect => {
return None;
}
})
@@ -542,6 +551,9 @@ impl Item {
pub fn description(self) -> &'static str {
match self {
Item::Fullbright => "Show blocks and entities at full light, even in dark areas.",
Item::DynamicLights => {
"Torches and other light sources held, dropped or on fire light the blocks around them."
}
Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.",
Item::ZoomKey => "Click, then press a key. Escape unbinds it.",
Item::ZoomLevel => "The zoom the key starts at.",
@@ -581,7 +593,7 @@ impl Item {
use crate::graphics_style::Cost;
match self {
Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
Item::Minimap => Some(Cost::Low),
Item::Minimap | Item::DynamicLights => Some(Cost::Low),
Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None),
_ => None,
}
@@ -590,6 +602,7 @@ impl Item {
pub fn switch(self, e: &Extras) -> Option<bool> {
Some(match self {
Item::Fullbright => e.fullbright,
Item::DynamicLights => e.dynamic_lights,
Item::Zoom => e.zoom,
Item::ZoomSmooth => e.zoom_smooth,
Item::ZoomSensitivity => e.zoom_sensitivity,
@@ -632,6 +645,7 @@ impl Item {
pub fn cycle(self, e: &mut Extras, back: bool) {
match self {
Item::Fullbright => e.fullbright = !e.fullbright,
Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights,
Item::Zoom => e.zoom = !e.zoom,
Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth,
Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity,
@@ -677,7 +691,7 @@ mod tests {
#[test]
fn everything_is_off_by_default_and_round_trips() {
let d = Extras::default();
assert!(!d.fullbright);
assert!(!d.fullbright && !d.dynamic_lights);
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
assert!(!d.mouse_tweaks && !d.sort);
assert_eq!(Extras::parse(""), d);
@@ -685,6 +699,9 @@ mod tests {
let mut e = d.clone();
Item::Fullbright.cycle(&mut e, false);
assert_eq!(Item::Fullbright.switch(&e), Some(true));
Item::DynamicLights.cycle(&mut e, false);
assert_eq!(Item::DynamicLights.switch(&e), Some(true));
assert_eq!(Extras::parse(&e.serialize()), e);
e.zoom = true;
e.zoom_key = "key.keyboard.c".into();
e.zoom_level = 6;
@@ -21,6 +21,8 @@ pub enum ItemPose {
Trident {
ticks_used: f32,
},
/// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork.
SpinAttack,
Bow {
ticks_used: f32,
},
@@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
if matches!(pose, ItemPose::Using) {
return m;
}
if matches!(pose, ItemPose::SpinAttack) {
return m
* Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3))
* Mat4::from_rotation_y((invert * 65.0f32).to_radians())
* Mat4::from_rotation_z((invert * -85.0f32).to_radians());
}
let charging = match pose {
ItemPose::Bow { ticks_used } => {
let power = ticks_used / 20.0;
+385 -86
View File
@@ -34,9 +34,11 @@ mod crossbow;
mod debug_keys;
mod decorated_pot;
mod dedicated;
mod deflect;
mod dispense_fixture;
mod dispenser;
mod dragon;
mod dynamic_lights;
mod enchant_effects;
mod end;
mod entity_culling;
@@ -72,6 +74,7 @@ mod lan_entities;
mod lan_mobs;
mod lan_pvp;
mod lan_screen;
mod lan_stations;
mod lan_trading;
mod lan_waypoints;
mod leads;
@@ -89,6 +92,7 @@ mod mob_gear;
mod mods;
mod mount_menu;
mod mounts;
mod moving_pistons;
mod music;
mod names;
mod natural_spawning;
@@ -116,6 +120,7 @@ mod recipe_book;
mod remote;
mod remote_objects;
mod remote_projectiles;
mod remote_stations;
mod render_control;
mod render_tick;
mod respawn_anchor;
@@ -267,8 +272,9 @@ struct Options {
benchmark: Option<String>,
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
dev_mods: Vec<PathBuf>,
/// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on
/// an integrated server thread (game/integrated.rs).
/// Single player runs on an integrated server thread (game/integrated.rs),
/// as vanilla's does: the default. `--no-server-thread` or
/// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead.
server_thread: bool,
/// Set on the integrated server's own options: it draws nothing, so it skips meshing.
integrated: bool,
@@ -323,7 +329,10 @@ impl Options {
dedicated: None,
benchmark: None,
dev_mods: Vec::new(),
server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"),
// The command harness (HORIZON_COMMAND_SCRIPT) drives the world
// itself, without the event loop: it stays in the frame.
server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0")
&& std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(),
integrated: false,
};
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
@@ -332,7 +341,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
horizon_core::VANILLA_VERSION
);
return Ok(None);
@@ -347,6 +356,7 @@ impl Options {
"--offscreen" => o.offscreen = true,
"--control" => o.control = Some(horizon_client::control::default_path()),
"--server-thread" => o.server_thread = true,
"--no-server-thread" => o.server_thread = false,
_ => {
let value = args
.next()
@@ -894,6 +904,8 @@ struct WorldRest {
behaviours: Behaviours,
player_arm: Option<horizon_client::mobs::Part>,
player_type: Option<Arc<horizon_client::mobs::MobType>>,
/// `SpinAttackEffectModel` (Riptide's spinning boxes).
spin_attack: Option<horizon_client::mobs::Part>,
stations: horizon_client::stations::StationData,
}
@@ -969,6 +981,9 @@ impl Resources {
fn player_type(&self) -> &Option<Arc<horizon_client::mobs::MobType>> {
&self.rest().player_type
}
fn spin_attack(&self) -> &Option<horizon_client::mobs::Part> {
&self.rest().spin_attack
}
fn stations(&self) -> &horizon_client::stations::StationData {
&self.rest().stations
}
@@ -1136,6 +1151,9 @@ struct Game<'a> {
potions: potions::PotionState,
scratch_slot: Option<ItemStack>,
mining: Option<Mining>,
/// The other players' cracks (`LevelRenderer.destroyingBlocks`): breaker id to the block,
/// the stage (0..=9) and the game time it last changed.
destroying: HashMap<i32, ([i32; 3], u8, i64)>,
destroy_delay: u32,
use_delay: u32,
creative: bool,
@@ -1174,6 +1192,10 @@ struct Game<'a> {
renderer: Option<Renderer>,
/// CPU geometry storage retained across frames, including empty/title frames.
entity_vertices: Vec<Vertex>,
/// Horizon Extras' dynamic lights this frame (`dynamic_lights.rs`), and how brightly each
/// item glows (built the first time the extra is on).
dynamic_lights: Vec<[f32; 4]>,
luminance: Option<horizon_client::dynamic_light::Luminance>,
/// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`).
see_through_vertices: Vec<Vertex>,
started: Instant,
@@ -1233,7 +1255,9 @@ struct Game<'a> {
/// swap just before an attack keeps them, with the new item's enchantments
/// (attribute swapping).
attack_item: Option<Arc<str>>,
last_hurt_by_player: HashSet<u32>,
/// Mobs a player hurt (`LivingEntity.lastHurtByPlayer`), with the guest
/// it was by connection (None: the host).
last_hurt_by_player: HashMap<u32, Option<u32>>,
/// Mobs whose death (`LivingEntity.die`) has been handled.
died: HashSet<u32>,
/// Client-ticked block-entity animation state (`game/block_entity_anims.rs`).
@@ -1393,6 +1417,8 @@ struct Game<'a> {
arrow_model: Option<horizon_client::mobs::Part>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
/// Where item entities are, while the block entities tick (hoppers).
item_columns: Option<machines::ItemColumns>,
creative_screen: Creative,
control: Option<horizon_client::control::Server>,
frame_stats: horizon_client::control::FrameStats,
@@ -2417,8 +2443,21 @@ impl Game<'_> {
b.run_block_events(level, ticks);
b.tick_block_entities(level, ticks);
});
self.sync_moving_pistons();
self.process_level_events()
}
/// Copies the moving-piston block entities into the world, where the
/// collision queries and the renderer read them.
fn sync_moving_pistons(&mut self) {
let pistons = &mut self.world.moving_pistons;
pistons.clear();
pistons.extend(
self.block_ticks
.moving_pistons
.iter()
.map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())),
);
}
/// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time:
/// the side effects of each (a shrieker summoning a warden, drops, game
/// events) happen before the next tick runs, as they do inline in vanilla.
@@ -2527,14 +2566,23 @@ impl Game<'_> {
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
1031 => Some(("minecraft:block.anvil.land", 0.3)),
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
1042 => Some(("minecraft:block.grindstone.use", 1.0)),
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
1043 => Some(("minecraft:item.book.page_turn", 1.0)),
_ => None,
};
if let Some((name, volume)) = sound {
let pitch = if id == 1009 {
2.6 + (self.world.random.next_float() - self.world.random.next_float())
* 0.8
} else {
1.0
let pitch = match id {
1009 => {
2.6 + (self.world.random.next_float()
- self.world.random.next_float())
* 0.8
}
1029 | 1030 | 1042 | 1043 | 1044 => {
self.world.random.next_float() * 0.1 + 0.9
}
_ => 1.0,
};
self.audio.play(name, c, volume, pitch);
}
@@ -3763,6 +3811,9 @@ impl Game<'_> {
f64::from(z) + 0.5,
));
self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]);
// The world's spawn from the start, not only once saved: a bed set
// before the first save must not become it.
self.level.world_spawn.get_or_insert([x, y, z]);
}
let s = self
.level
@@ -3884,6 +3935,7 @@ impl Game<'_> {
}
let riding = self.riding.is_some();
let ghast_collisions = self.happy_ghast_player_collisions();
let spin_targets = self.spin_targets();
let Some(player) = self.player.as_mut() else {
// A dedicated server has no local player: the world still runs.
if self.options.dedicated.is_some() {
@@ -3961,6 +4013,7 @@ impl Game<'_> {
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
// The dimension's FAST_LAVA: the Nether's lava pushes harder.
player.fluids.fast_lava = self.dim == Dim::Nether;
player.spin_targets = spin_targets;
let grounded = player.ground.on_ground;
let before = (
grounded,
@@ -3983,6 +4036,7 @@ impl Game<'_> {
}
}
let events = std::mem::take(&mut player.events);
let spin_hit = player.spin_hit.take();
let glider_wear = std::mem::take(&mut player.glider_wear);
if glider_wear > 0
&& !self.creative
@@ -4001,6 +4055,7 @@ impl Game<'_> {
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
self.tick_avatar(before, riding);
self.end_spin_attack(spin_hit);
self.record_combat(&events);
for event in events {
match event {
@@ -4432,10 +4487,17 @@ impl Game<'_> {
};
if capture {
self.mouse.set_ignore_first_move();
// macOS warps by re-associating the mouse with the pointer,
// which undoes a Locked grab and leaves the pointer free: warp
// first there. Wayland moves a pointer only while it is locked,
// so everywhere else warp after grabbing.
#[cfg(target_os = "macos")]
warp(window);
self.captured = window
.set_cursor_grab(CursorGrabMode::Locked)
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined))
.is_ok();
#[cfg(not(target_os = "macos"))]
if self.captured && self.focused {
warp(window);
}
@@ -5400,6 +5462,17 @@ impl Game<'_> {
.station
.as_ref()
.is_some_and(|s| s.kind == stations::Kind::Merchant);
let stonecutter_open = self
.station
.as_ref()
.is_some_and(|s| s.kind == stations::Kind::Stonecutter);
let station_kind = self.station.as_ref().map(|s| s.kind);
let grindstone_open = station_kind == Some(stations::Kind::Grindstone);
let cartography_open = station_kind == Some(stations::Kind::Cartography);
let anvil_open = station_kind == Some(stations::Kind::Anvil);
let smithing_open = station_kind == Some(stations::Kind::Smithing);
let enchanting_open = station_kind == Some(stations::Kind::Enchanting);
let beacon_open = station_kind == Some(stations::Kind::Beacon);
let (kind, game_of): (Kind, Vec<Option<usize>>) = if self.creative_tab_open() {
// ItemPickerMenu: the display slots (clicked by the screen), then the hotbar.
let mut v = vec![None; 45];
@@ -5426,6 +5499,51 @@ impl Game<'_> {
v.push(Some(stations::RESULT));
v.extend((9..36).chain(0..9).map(Some));
(Kind::Loom, v)
} else if stonecutter_open {
// StonecutterMenu: the input, the result, then the inventory.
let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Stonecutter, v)
} else if grindstone_open || cartography_open {
// GrindstoneMenu and CartographyTableMenu: the two inputs, the
// result, then the inventory.
let mut v = vec![
Some(stations::INPUT),
Some(stations::INPUT + 1),
Some(stations::RESULT),
];
v.extend((9..36).chain(0..9).map(Some));
let kind = if grindstone_open {
Kind::Grindstone
} else {
Kind::Cartography
};
(kind, v)
} else if enchanting_open {
// EnchantmentMenu: the item, the lapis, then the inventory.
let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Enchanting, v)
} else if beacon_open {
// BeaconMenu: the payment, then the inventory.
let mut v = vec![Some(stations::INPUT)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Beacon, v)
} else if anvil_open || smithing_open {
// ItemCombinerMenu: the inputs, the result, then the inventory.
let inputs = if anvil_open { 2 } else { 3 };
let mut v: Vec<Option<usize>> =
(0..inputs).map(|i| Some(stations::INPUT + i)).collect();
v.push(Some(stations::RESULT));
v.extend((9..36).chain(0..9).map(Some));
(
if anvil_open {
Kind::Anvil
} else {
Kind::Smithing
},
v,
)
} else {
let (kind, map) = if self.container.is_some() {
let size = self.container_size();
@@ -5508,6 +5626,10 @@ impl Game<'_> {
s.loom.patterns.clone(),
)
});
let stone = self
.station
.as_ref()
.map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone()));
let crafter_data = match self.container_kind() {
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
_ => None,
@@ -5521,6 +5643,18 @@ impl Game<'_> {
if let Some((s, mob)) = session.as_mut() {
self.merchant_sync_in(s, *mob);
}
// The cartography table reads and makes the level's maps; a
// server's (the client menu's ContainerLevelAccess.NULL) doesn't.
let level_maps = (kind == Kind::Cartography && self.remote.is_none()).then(|| {
let held: Vec<ItemStack> = before
.iter()
.flatten()
.chain(self.inventory.iter().flatten())
.chain(self.carried.iter())
.cloned()
.collect();
self.level_maps(&held)
});
let next_map = if merchant_open { self.peek_map_id() } else { 0 };
let tag = |t: &str| self.structure_tag(t);
let maps = trading::GameMaps {
@@ -5539,10 +5673,21 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: Some(&trade_env),
maps: level_maps
.as_ref()
.map(|m| m as &dyn horizon_client::menu::Maps),
};
menu.creative = creative;
menu.selected = self.selected;
menu.levels = self.experience.level;
if anvil_open {
// The rename box as AnvilScreen.onNameChanged gives it to the menu.
menu.anvil.name = self.station.as_ref().map(|s| self.anvil_item_name(s));
}
for (i, stack) in before.iter().enumerate() {
menu.set_slot(&env, i, stack.clone());
}
@@ -5560,6 +5705,25 @@ impl Game<'_> {
menu.loom_patterns = patterns;
menu.set_slot(&env, 3, before[3].clone());
}
if kind == Kind::Stonecutter
&& let Some((selected, state)) = stone
{
// The same: the list and selection between clicks, then the result.
menu.data[0] = selected;
menu.stone = state;
menu.set_slot(&env, 1, before[1].clone());
}
if kind == Kind::Enchanting
&& let Some(s) = self.station.as_ref()
{
// The offers between clicks (what copying the slots in flagged is not a change).
menu.enchant_changed = false;
for i in 0..3 {
menu.data[i] = s.offers.costs[i];
menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32);
}
menu.data[3] = self.level.xp_seed;
}
if let Some((disabled, triggered)) = crafter_data {
for (i, d) in disabled.iter().enumerate() {
menu.data[i] = i32::from(*d);
@@ -5614,10 +5778,37 @@ impl Game<'_> {
s.loom.selected = usize::try_from(menu.data[0]).ok();
s.loom.patterns = std::mem::take(&mut menu.loom_patterns);
}
for sound in sounds {
self.loom_sound(sound);
// A server's loom plays its own sounds (the client's menu has no level).
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
self.loom_screen_changed();
} else if kind == Kind::Cartography {
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
} else if kind == Kind::Stonecutter {
if let Some(s) = self.station.as_mut() {
s.selected = usize::try_from(menu.data[0]).ok();
s.stone = std::mem::take(&mut menu.stone);
s.stonecutter_changed();
}
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
}
if let Some(amount) = menu.ground.take().filter(|_| !predicting)
&& let Some(pos) = self.station.as_ref().map(|s| s.pos)
{
self.grindstone_taken(pos, amount);
}
if kind == Kind::Anvil || kind == Kind::Smithing {
self.combiner_session_end(&menu, predicting);
}
if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned())
{
// EnchantmentMenu.slotsChanged: new offers for the item.
self.station_changed();
}
if kind == Kind::CrafterBlock
&& let Some(BlockEntity::Crafter(c)) = self
@@ -5645,6 +5836,9 @@ impl Game<'_> {
}
}
self.apply_equipment();
if let Some(maps) = level_maps {
self.register_made_maps(maps);
}
true
}
/// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar
@@ -6468,19 +6662,11 @@ impl Game<'_> {
.block_entity_render()
.render(&scene, visible, &mut out);
}
if let Some(mining) = &self.mining
&& mining.progress > 0.0
&& self.gui.atlas.sprites.contains_key(&format!(
"block/destroy_stage_{}",
((mining.progress * 10.0) as u32).min(9)
))
{
let state = self
.world
.block(mining.pos[0], mining.pos[1], mining.pos[2]);
for (pos, stage) in self.cracks(camera) {
let state = self.world.block(pos[0], pos[1], pos[2]);
self.res
.block_entity_render()
.render_breaking(&scene, mining.pos, state.0, &mut out);
.render_breaking(&scene, pos, state.0, stage, &mut out);
}
}
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
@@ -6577,6 +6763,7 @@ impl Game<'_> {
vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint);
}
}
self.moving_piston_geometry(camera, alpha, &mut out);
self.tnt_geometry(camera, alpha, &mut out);
self.painting_geometry(camera, &mut out);
self.frame_geometry(camera, &mut out);
@@ -6588,6 +6775,7 @@ impl Game<'_> {
self.leash_geometry(camera, alpha, &mut out);
self.trident_geometry(camera, alpha, &mut out);
self.rocket_geometry(camera, alpha, &mut out);
self.thrown_potion_geometry(camera, alpha, &mut out);
// Particles (ParticleEngine.extract): camera-facing quads.
let world = &self.world;
self.particles.render(
@@ -6598,50 +6786,90 @@ impl Game<'_> {
&|b| world.light(b[0], b[1], b[2]),
&mut out,
);
let atlas = &self.gui.atlas;
// Breaking progress overlay (destroy_stage_0..9).
if let Some(m) = &self.mining
&& m.progress > 0.0
{
let stage = ((m.progress * 10.0) as u32).min(9);
if atlas
.sprites
.contains_key(&format!("block/destroy_stage_{stage}"))
// Breaking progress overlays (destroy_stage_0..9): ours and the other players'.
for (pos, stage) in self.cracks(camera) {
let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
- camera)
.as_vec3();
let state = self.world.block(pos[0], pos[1], pos[2]);
if self.res.facts().get(state).render_shape
== horizon_client::blocks::RenderShape::Model
&& let Ok(models) = self
.pack
.render
.model_catalog
.collect(state, BlockPos::new(pos[0], pos[1], pos[2]))
{
let o = (glam::DVec3::new(
f64::from(m.pos[0]),
f64::from(m.pos[1]),
f64::from(m.pos[2]),
) - camera)
.as_vec3();
let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]);
if self.res.facts().get(state).render_shape
== horizon_client::blocks::RenderShape::Model
&& let Ok(models) = self
.pack
.render
.model_catalog
.collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2]))
{
let offset = self
.pack
.context
.tables
.offset(state, m.pos[0], m.pos[2])
.unwrap_or([0.0; 3]);
let origin = o + glam::DVec3::from(offset).as_vec3();
let translucent = models
.iter()
.any(|(_, model)| model.faces.iter().any(|f| f.translucent));
for (_, model) in models {
horizon_client::breaking::geometry(model, origin, translucent, &mut out);
}
let offset = self
.pack
.context
.tables
.offset(state, pos[0], pos[2])
.unwrap_or([0.0; 3]);
let origin = o + glam::DVec3::from(offset).as_vec3();
let translucent = models
.iter()
.any(|(_, model)| model.faces.iter().any(|f| f.translucent));
for (_, model) in models {
horizon_client::breaking::geometry(model, origin, translucent, stage, &mut out);
}
}
}
out
}
/// `LevelRenderer.destroyBlockProgress`: a player's crack on a block (0..=9), or none
/// (any other progress). Cracks not updated for 400 ticks are dropped.
pub(crate) fn destroy_block_progress(&mut self, breaker: i32, pos: [i32; 3], progress: i32) {
let now = self.world.game_time;
self.destroying
.retain(|_, c| now.saturating_sub(c.2) <= 400);
if (0..10).contains(&progress) {
self.destroying.insert(breaker, (pos, progress as u8, now));
} else {
self.destroying.remove(&breaker);
}
}
/// The cracks to draw and their stage sprite's atlas origin: our own mining and the
/// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the
/// furthest progress on each block).
fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> {
let mut stages: Vec<([i32; 3], u32)> = Vec::new();
let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) {
Some(c) => c.1 = c.1.max(stage),
None => stages.push((pos, stage)),
};
if let Some(m) = &self.mining
&& m.progress > 0.0
{
add(m.pos, ((m.progress * 10.0) as u32).min(9));
}
let now = self.world.game_time;
for (pos, stage, at) in self.destroying.values() {
if now.saturating_sub(*at) <= 400 {
add(*pos, u32::from(*stage));
}
}
stages
.into_iter()
.filter(|(pos, _)| {
let d = glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
+ 0.5
- camera;
d.length_squared() <= 1024.0
})
.filter_map(|(pos, stage)| {
let r = self
.gui
.atlas
.sprites
.get(&format!("block/destroy_stage_{stage}"))?;
Some((pos, [r.u0, r.v0]))
})
.collect()
}
fn sky_darken(&self) -> i32 {
if self.dim == Dim::Nether {
return 11;
@@ -6694,7 +6922,13 @@ impl Game<'_> {
/// enchantments.
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage);
let damage = hand_damage + self.effect_attack_bonus();
// Riptide's spin replaces the attack damage attribute.
let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg);
let damage = if spin > 0.0 {
spin
} else {
hand_damage + self.effect_attack_bonus()
};
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
@@ -6791,6 +7025,10 @@ impl Game<'_> {
self.break_painting(i, true);
return true;
}
// A ghast's fireball or a wind charge in front: turned back.
if self.attack_redirectable() {
return true;
}
let hand_damage = 1.0
+ self
.held()
@@ -6818,6 +7056,14 @@ impl Game<'_> {
return false;
}
}
self.attack_mob(index);
// Minecraft.startAttack swings after the attack.
self.swing_arm();
true
}
/// `Player.attack` on a mob: the damage, knockback, sweep, particles and
/// sounds.
pub(super) fn attack_mob(&mut self, index: usize) {
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
let (amount, scale, crit) = self.melee_damage(&target_kind);
@@ -6835,7 +7081,6 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0);
}
self.swing_arm();
// LivingEntity.setLastHurtMob (tamed wolves join in).
self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
let old_health = self.mobs[index].health;
@@ -6843,7 +7088,24 @@ impl Game<'_> {
Some(f) => self.attack_source(f),
None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic),
};
if self.hurt_by_player(index, amount, source) {
let landed = self.hurt_by_player(index, amount, source);
if let Some(p) = self.player.as_mut() {
if p.attack_log.len() >= 64 {
p.attack_log.remove(0);
}
p.attack_log.push(horizon_client::health::AttackRecord {
game_time: p.health.game_time(),
target: target_kind.clone(),
id: self.mobs[index].id,
killed: landed && !self.mobs[index].alive(),
amount,
scale,
crit,
landed,
dealt: old_health - self.mobs[index].health,
});
}
if landed {
if knockback > 0.0 {
let (xd, zd) = self.extra_knockback_direction();
self.mobs[index].knockback(f64::from(knockback), xd, zd);
@@ -6882,7 +7144,8 @@ impl Game<'_> {
(actual * 0.5) as u32,
);
}
self.last_hurt_by_player.insert(self.mobs[index].id);
self.last_hurt_by_player
.insert(self.mobs[index].id, self.lan_acting);
let sound = if crit {
"minecraft:entity.player.attack.crit"
} else if scale > 0.9 {
@@ -6910,7 +7173,6 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
}
true
}
/// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step.
/// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the
@@ -8410,6 +8672,10 @@ impl Game<'_> {
}
let shown = self.hands_to_render();
let used_hand = self.used_hand();
let spinning = self
.player
.as_ref()
.is_some_and(|p| p.auto_spin_attack_ticks > 0);
for (i, (hand, item)) in Hand::BOTH
.into_iter()
.zip(self.visible_hand_items())
@@ -8529,6 +8795,7 @@ impl Game<'_> {
ItemPose::Using
}
}
_ if spinning => ItemPose::SpinAttack,
_ => ItemPose::Swing,
};
let m = to_world
@@ -9349,7 +9616,7 @@ impl Game<'_> {
),
};
self.audio
.set_listener([camera.x, camera.y, camera.z], view_yaw);
.set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch);
let block = [
camera.x.floor() as i32,
camera.y.floor() as i32,
@@ -9581,6 +9848,11 @@ impl Game<'_> {
.then(|| self.border_draw(camera.to_array(), alpha as f32))
.flatten();
let see_through = std::mem::take(&mut self.see_through_vertices);
if title {
self.dynamic_lights.clear();
} else {
self.gather_dynamic_lights(camera, alpha);
}
let frame = Frame {
shader: self.shader_inputs(camera, alpha as f32),
nether_lighting: self.dim == Dim::Nether,
@@ -9638,6 +9910,7 @@ impl Game<'_> {
color: sky.cloud_color,
}),
entities: &entities,
dynamic_lights: &self.dynamic_lights,
additive: &additive,
see_through: &see_through,
celestial: if self.settings.horizon.sky || title {
@@ -9653,14 +9926,10 @@ impl Game<'_> {
game_time: self.world.game_time as f32,
shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0,
crumbling_sprite: self
.mining
.as_ref()
.and_then(|m| {
self.gui.atlas.sprites.get(&format!(
"block/destroy_stage_{}",
((m.progress * 10.0) as u32).min(9)
))
})
.gui
.atlas
.sprites
.get("block/destroy_stage_0")
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]),
end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| {
self.gui
@@ -10858,6 +11127,10 @@ impl ApplicationHandler for Game<'_> {
WindowEvent::RedrawRequested => {
self.observe_fullscreen();
let now = Instant::now();
let frame_cpu = self
.options
.spikes
.and_then(|_| horizon_client::spans::thread_cpu());
let elapsed = now.duration_since(self.previous);
self.frame_ticks = elapsed.as_secs_f32() * 20.0;
self.previous = now;
@@ -10887,6 +11160,8 @@ impl ApplicationHandler for Game<'_> {
}
let updated = Instant::now();
self.track_toggle_screens();
// For the "I'm playing" ping: an atomic, sent on when it changes.
horizon_client::heartbeat::set_lan(self.is_published());
let steps = self.clock.advance(elapsed);
for _ in 0..steps {
let started = Instant::now();
@@ -10924,15 +11199,16 @@ impl ApplicationHandler for Game<'_> {
let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0;
let spans = horizon_client::spans::take();
if cpu > threshold {
let list: Vec<String> = spans
.iter()
.filter(|(_, ms)| *ms >= 0.5)
.map(|(n, ms)| format!("{n} {ms:.1}"))
.collect();
// The render thread's own CPU time in the frame:
// far below the wall time, the frame waited.
let worked = horizon_client::spans::thread_cpu()
.zip(frame_cpu)
.map_or_else(String::new, |(end, start)| {
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
});
log::info!(
"Horizon: slow frame {cpu:.1} ms ({} ticks): {}",
steps,
list.join(", ")
"Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}",
horizon_client::spans::describe(&spans)
);
}
}
@@ -11202,6 +11478,7 @@ impl<'a> Game<'a> {
potions: Default::default(),
scratch_slot: None,
mining: None,
destroying: HashMap::new(),
destroy_delay: 0,
use_delay: 0,
creative,
@@ -11231,6 +11508,8 @@ impl<'a> Game<'a> {
window: None,
renderer: None,
entity_vertices: Vec::new(),
dynamic_lights: Vec::new(),
luminance: None,
see_through_vertices: Vec::new(),
health_hud: hud_layout::HealthHud::default(),
started: now,
@@ -11271,7 +11550,7 @@ impl<'a> Game<'a> {
raiding: Default::default(),
attack_ticks: 100,
attack_item: None,
last_hurt_by_player: HashSet::new(),
last_hurt_by_player: HashMap::new(),
died: HashSet::new(),
be_anims: {
let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default();
@@ -11381,6 +11660,7 @@ impl<'a> Game<'a> {
arrow_model: prepared.arrow_model,
tnts: Vec::new(),
hoppers: HashMap::new(),
item_columns: None,
creative_screen: prepared.creative_screen,
control: None,
frame_stats: Default::default(),
@@ -11976,6 +12256,7 @@ fn load_world_rest(
player_type: perspective::player_type(root),
player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main")
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"),
})
}
@@ -12104,6 +12385,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
hud,
nether_lighting: false,
entities: &[],
dynamic_lights: &[],
clouds: None,
additive: &[],
see_through: &[],
@@ -12677,9 +12959,26 @@ pub fn run() -> Result<()> {
if options.dedicated.is_some() && !dedicated::preflight(&mut options)? {
return Ok(());
}
if options.dedicated.is_some() {
// Before any worker starts: on Linux they go behind the server thread.
horizon_threads::put_helpers_behind();
// Before any worker starts: on Linux they go behind the server thread
// and the render thread.
horizon_threads::put_helpers_behind();
if options.dedicated.is_none() {
// The render thread, like the server thread, ahead of the workers on
// macOS and Windows. While terrain loads, the worker pools (two with
// single player's server thread) and other programs outnumber the
// cores, and a frame that gave its core up (in a GPU submit) waited
// 10 to 200 ms to get one back.
horizon_threads::favour_current();
}
// Someone is playing: the anonymous ping behind the launcher's "N playing now". Not for a
// server, a benchmark or a run that quits by itself.
if options.dedicated.is_none()
&& options.benchmark.is_none()
&& !options.offscreen
&& options.frames.is_none()
&& options.world_frames.is_none()
{
horizon_client::heartbeat::start();
}
let started = Instant::now();
horizon_client::spans::enable(options.spikes.is_some());
+52 -7
View File
@@ -91,6 +91,8 @@ pub(super) struct AdvState {
/// The tree being read on another thread since the world opened
/// (`prefetch_advancement_tree`), taken by the first `advancement_tree`.
pub(super) pending_tree: Option<std::thread::JoinHandle<Tree>>,
/// `inventory_changed`'s criteria by item, built for `tree`.
inventory_index: Option<(Arc<Tree>, Arc<adv::InventoryIndex>)>,
}
/// The game's world for predicates.
struct View<'a, 'g>(&'a Game<'g>);
@@ -229,9 +231,31 @@ impl Game<'_> {
_ => Tree::load(&self.options.resources.join("data")),
};
self.adv.tree = Arc::new(tree);
// With the tree, while the world loads: built on the first
// inventory change it cost that tick ~10 ms.
self.inventory_index();
}
self.adv.tree.clone()
}
/// `inventory_changed`'s criteria by item, for the tree in place.
fn inventory_index(&mut self) -> Arc<adv::InventoryIndex> {
let tree = self.adv.tree.clone();
if let Some((built, index)) = &self.adv.inventory_index
&& Arc::ptr_eq(built, &tree)
{
return index.clone();
}
let items = self.res.items();
let index = Arc::new(adv::InventoryIndex::build(&tree, |tag| {
items
.item_tags
.get(tag)
.map(|t| t.iter().map(String::as_str).collect())
.unwrap_or_default()
}));
self.adv.inventory_index = Some((tree, index.clone()));
index
}
/// Start reading the advancement files on another thread while the world
/// loads. The first tick's first criterion trigger used to read and parse
/// all of them on the game thread (about 60 ms).
@@ -394,6 +418,16 @@ impl Game<'_> {
let Some(list) = tree.by_trigger.get(name) else {
return;
};
self.trigger_criteria(&tree, list, test);
}
/// `trigger` for some of a trigger's criteria: (advancement, criterion)
/// indexes in `tree`, in tree order.
fn trigger_criteria(
&mut self,
tree: &Tree,
list: &[(usize, usize)],
test: impl Fn(&Value, &dyn adv::World) -> bool,
) {
let mut hits = Vec::new();
{
let view = View(self);
@@ -437,9 +471,14 @@ impl Game<'_> {
} else {
self.recipe_toast(unlocked);
}
if unlocked.is_empty() || self.remote.is_some() || self.no_player_here() {
return;
}
self.load_advancements();
let tree = self.adv.tree.clone();
for r in unlocked {
let r = r.clone();
self.trigger("minecraft:recipe_unlocked", move |c, _| {
let list = tree.recipe_criteria(r);
self.trigger_criteria(&tree, &list, |c, _| {
c["recipes"].as_str() == Some(r.as_str())
});
}
@@ -560,7 +599,15 @@ impl Game<'_> {
.is_some_and(|i| s.count >= i.max_stack)
})
.count() as f64;
self.trigger("minecraft:inventory_changed", move |c, w| {
// Only the criteria the items held could pass (`InventoryIndex`).
if self.remote.is_some() || self.no_player_here() {
return;
}
self.load_advancements();
let tree = self.adv.tree.clone();
let index = self.inventory_index();
let list = index.candidates(stacks.iter().map(|s| s.id.as_str()));
self.trigger_criteria(&tree, &list, move |c, w| {
let slots = &c["slots"];
let range = |k: &str, v: f64| {
let r = &slots[k];
@@ -965,10 +1012,8 @@ impl Game<'_> {
});
positions.push((a.x, a.y));
}
let mut tree = Tree {
list,
..Tree::default()
};
let mut tree = Tree::default();
tree.list = list;
for (i, a) in tree.list.iter().enumerate() {
tree.by_id.insert(a.id.clone(), i);
}
+11 -1
View File
@@ -1840,11 +1840,21 @@ impl Game<'_> {
if self.ticks < *report_tick && !timed_out {
return None;
}
let after = pos.map(|p| self.block_json(p));
let changed = match (*pos, *before) {
(Some(p), Some(b)) => self.world.block(p[0], p[1], p[2]) != b,
_ => false,
};
// A client of a server (single player's server thread, a LAN
// guest) sees the block once the server's answer comes.
if *place
&& !changed
&& self.remote.is_some()
&& self.ticks < *report_tick + 20
&& !timed_out
{
return None;
}
let after = pos.map(|p| self.block_json(p));
let used = delta(inventory, &self.inventory_counts());
let mut v = json!({
"ok": !*place || changed,
+16 -6
View File
@@ -9,18 +9,28 @@ impl Game<'_> {
pub(super) fn tick_allays(&mut self) {
let griefing = self.ui.rules.bool("mob_griefing");
let player = self.player.as_ref().map(|p| p.position);
// The playing jukeboxes, found at the first allay: no allay starts
// or stops one, and the block entities run into the thousands.
let mut jukeboxes: Option<Vec<(i32, i32, i32)>> = None;
for i in 0..self.mobs.len() {
if self.mobs[i].species() != Species::Allay || !self.mobs[i].alive() {
continue;
}
let pos = self.mobs[i].position;
// Dancing: a playing jukebox within 10 blocks.
let dancing = self.world.block_entities.iter().any(|(k, e)| {
matches!(e, BlockEntity::Jukebox(j) if j.playing)
&& (f64::from(k.0) + 0.5 - pos.x).powi(2)
+ (f64::from(k.1) + 0.5 - pos.y).powi(2)
+ (f64::from(k.2) + 0.5 - pos.z).powi(2)
<= 100.0
let jukeboxes = jukeboxes.get_or_insert_with(|| {
self.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Jukebox(j) if j.playing))
.map(|(k, _)| *k)
.collect()
});
let dancing = jukeboxes.iter().any(|k| {
(f64::from(k.0) + 0.5 - pos.x).powi(2)
+ (f64::from(k.1) + 0.5 - pos.y).powi(2)
+ (f64::from(k.2) + 0.5 - pos.z).powi(2)
<= 100.0
});
self.mobs[i].extra.flag =
dancing && !horizon_client::mobs::goals::should_panic(&self.mobs[i]);
+16 -6
View File
@@ -15,6 +15,7 @@ use horizon_client::{
mesher::Vertex,
mobs::render::{DYE, DYE_NAMES},
};
use horizon_protocol::packets::play::{self, Serverbound as S};
/// The beacon screen is 54 px wider than the 176-px menus it shares an origin with.
pub(super) const SHIFT: f32 = -27.0;
@@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [
"minecraft:diamond",
"minecraft:netherite_ingot",
];
pub(super) fn is_payment(item: &str) -> bool {
PAYMENT.contains(&item)
}
/// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin.
pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> {
Some(match i {
@@ -171,7 +169,7 @@ impl Game<'_> {
}
}
}
fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
let at = [
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
@@ -255,9 +253,13 @@ impl Game<'_> {
}
}
fn beacon_levels(&self) -> i32 {
let Some(pos) = self.station.as_ref().map(|s| s.pos) else {
let Some(s) = self.station.as_ref() else {
return 0;
};
if let Some(levels) = s.beacon_levels {
return levels;
}
let pos = s.pos;
match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) {
Some(BlockEntity::Beacon(b)) => b.levels,
_ => 0,
@@ -346,8 +348,16 @@ impl Game<'_> {
self.screen = super::Screen::Playing;
self.capture(true);
}
/// `BeaconMenu.updateEffects`: spend the payment and set the powers.
/// `BeaconMenu.updateEffects`: spend the payment and set the powers. On
/// a server, `BeaconScreen`'s confirm button sends them
/// (`ServerboundSetBeaconPacket`) and the server's menu does it.
fn confirm_beacon(&mut self, sel: [Option<usize>; 2]) {
if self.remote.is_some() {
let id = |e: Option<usize>| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0));
let (primary, secondary) = (id(sel[0]), id(sel[1]));
self.send(S::SetBeacon(play::SetBeacon { primary, secondary }));
return;
}
let Some(s) = self.station.as_mut() else {
return;
};
@@ -24,6 +24,7 @@ impl Game<'_> {
let ticking = self.block_ticking_area();
let mut spawners = Vec::new();
let mut trial_spawners = Vec::new();
self.item_columns = Some(Default::default());
for slot in self.world.block_entity_tickers() {
let pos = slot.0;
// Ticks before this one can remove it (`TickingBlockEntity.isRemoved`).
@@ -56,6 +57,8 @@ impl Game<'_> {
_ => {}
}
}
// Items move between passes: the columns hold for this one only.
self.item_columns = None;
self.update_song_volumes();
self.scan_for_hearts();
// The client ticks (particles, sounds, the turning mob) are for a
+20
View File
@@ -141,6 +141,8 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> {
pub(super) struct BoatModels {
pub models: HashMap<String, Part>,
pub chest_models: HashMap<String, Part>,
/// `ModelLayers.BOAT_WATER_PATCH`, shared by every boat (not rafts).
pub water_patch: Option<Part>,
}
impl BoatModels {
/// Whether a boat of this wood (with or without a chest) can be drawn.
@@ -175,6 +177,7 @@ impl BoatModels {
Self {
models,
chest_models,
water_patch: document.and_then(|d| d.model("minecraft:boat#water_patch")),
}
}
}
@@ -785,6 +788,23 @@ impl Game<'_> {
0,
out,
);
// BoatRenderer.submitTypeAdditions: the water patch hides the water
// inside the hull unless the boat is under water (RaftRenderer has none).
if let Some(patch) = self.boat_models.water_patch.as_ref()
&& &*b.wood != "bamboo"
&& !matches!(b.status, Status::UnderWater | Status::UnderFlowingWater)
{
horizon_client::mobs::render::draw(
patch,
base,
&Poses::new(patch),
uv,
0xFFFF_FFFF,
packed,
horizon_client::gfx::WATER_MASK_OVERLAY,
out,
);
}
self.cull_entity_vertices(out, entity_start);
}
}
+206 -39
View File
@@ -9,6 +9,7 @@ use horizon_client::{
hud::{HudBatch, rgba},
item_data::WrittenBook,
items::ItemStack,
menu::{Kind, Menu},
text::Text,
ui,
};
@@ -89,6 +90,17 @@ impl Game<'_> {
self.capture(false);
}
pub(super) fn close_book(&mut self) {
// A server's lectern: LecternScreen's menu closes (closeContainer).
if matches!(
self.book,
Some(BookScreen::View {
lectern: Some(_),
..
})
) && self.remote.is_some()
{
self.remote_close_container();
}
self.book = None;
self.capture(true);
}
@@ -319,38 +331,25 @@ impl Game<'_> {
}
}
Some(BookScreen::View {
pages,
page,
lectern,
}) => {
let before = *page;
lectern: Some(key), ..
}) => lectern_page = Some(*key),
Some(BookScreen::View { pages, page, .. }) => {
if forward && *page + 1 < pages.len() {
*page += 1;
} else if !forward && *page > 0 {
*page -= 1;
}
if *page != before
&& let Some(pos) = *lectern
{
lectern_page = Some((pos, *page));
}
}
None => return,
}
// LecternScreen's page buttons click the menu's (1 back, 2 forward);
// the page turns with the server's data slot and level event 1043.
if let Some(key) = lectern_page {
self.lectern_button(key, if forward { 2 } else { 1 });
return;
}
self.audio
.play("minecraft:item.book.page_turn", None, 1.0, 1.0);
if let Some((pos, page)) = lectern_page {
self.set_lectern_page(pos, page as i32);
}
}
/// `LecternBlockEntity.setPage` and `LecternBlock.signalPageChange`.
fn set_lectern_page(&mut self, key: (i32, i32, i32), page: i32) {
if let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) {
l.page = page;
}
self.set_lectern_powered(key, true);
self.lectern_pulses.push((key, 2));
self.container_changed(key);
}
fn set_lectern_powered(&mut self, key: (i32, i32, i32), powered: bool) {
self.set_lectern_property(key, "powered", powered);
@@ -380,6 +379,7 @@ impl Game<'_> {
}
/// The 2-tick pulses of turned lecterns.
pub(super) fn tick_lecterns(&mut self) {
self.follow_lectern();
let mut done = Vec::new();
for (key, left) in &mut self.lectern_pulses {
*left -= 1;
@@ -452,6 +452,7 @@ impl Game<'_> {
.or_else(|| data.map(|d| d.writable_pages.clone()))
.unwrap_or_default();
let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
self.stats.custom("interact_with_lectern", 1);
self.open_book(BookScreen::View {
pages,
page,
@@ -459,24 +460,189 @@ impl Game<'_> {
});
true
}
/// `LecternMenu` "Take Book".
fn take_lectern_book(&mut self, key: (i32, i32, i32)) {
let book = match self.world.block_entities.get_mut(&key) {
Some(BlockEntity::Lectern(l)) => {
l.page = 0;
l.book.take()
/// A `LecternMenu` button of the open lectern screen: on a server it is
/// sent (`handleInventoryButtonClick`); here the lectern's menu takes it
/// with the player's inventory, and the screen follows the block entity.
fn lectern_button(&mut self, key: (i32, i32, i32), id: i32) {
if self.remote.is_some() {
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) {
self.send(
horizon_protocol::packets::play::Serverbound::ContainerButtonClick(
horizon_protocol::packets::play::ContainerButtonClick {
container: *container,
button: id,
},
),
);
}
_ => None,
};
if let Some(book) = book
&& let Some(rest) = self.give(book)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
return;
}
let Some(mut menu) = self.lectern_menu(key) else {
return;
};
for i in 0..36 {
menu.set_player_item(i, self.inventory[i].clone());
}
menu.set_player_item(40, self.offhand.clone());
menu.creative = self.creative;
menu.selected = self.selected;
menu.may_build = self.may_build();
if !menu.button(&self.menu_env(), id) {
return;
}
for i in 0..36 {
self.inventory[i] = menu.player_item(i).cloned();
}
self.offhand = menu.player_item(40).cloned();
for stack in std::mem::take(&mut menu.dropped) {
self.player_drop(stack);
}
self.lectern_menu_done(key, &menu);
self.follow_lectern();
}
/// The `book` control command: a button of the open book or lectern
/// screen (the page arrows, Take Book, Done), then its page.
pub(super) fn book_control(
&mut self,
action: Option<&str>,
) -> horizon_client::Result<serde_json::Value> {
let lectern = match &self.book {
Some(BookScreen::View { lectern, .. }) => *lectern,
Some(BookScreen::Edit { .. }) => None,
None => return Err("no book is open".into()),
};
match action {
None => {}
Some("next") => self.turn_page(true),
Some("back") => self.turn_page(false),
Some("take") => match lectern {
Some(key) => self.lectern_button(key, 3),
None => return Err("not a lectern".into()),
},
Some("done") => self.close_book(),
Some(other) => return Err(format!("unknown book button {other}").into()),
}
Ok(match &self.book {
Some(BookScreen::View {
pages,
page,
lectern,
}) => serde_json::json!({
"page": page, "pages": pages.len(), "lectern": lectern.map(|k| [k.0, k.1, k.2]),
}),
Some(BookScreen::Edit { pages, page, .. }) => {
serde_json::json!({ "page": page, "pages": pages.len(), "lectern": null })
}
None => serde_json::json!({ "closed": true }),
})
}
/// A server's `minecraft:lectern` menu: LecternScreen, its book and
/// page to come (`remote_lectern_book`, `remote_lectern_page`).
pub(super) fn remote_open_lectern(&mut self, key: (i32, i32, i32)) {
self.open_book(BookScreen::View {
pages: Vec::new(),
page: 0,
lectern: Some(key),
});
}
/// `LecternScreen.bookChanged`: the menu's book slot.
pub(super) fn remote_lectern_book(&mut self, book: Option<ItemStack>) {
if let Some(BookScreen::View {
lectern: Some(_),
pages,
page,
}) = self.book.as_mut()
{
let data = book.as_ref().and_then(ItemStack::data);
*pages = data
.and_then(|d| d.written.as_ref().map(|w| w.pages.clone()))
.or_else(|| data.map(|d| d.writable_pages.clone()))
.unwrap_or_default();
*page = (*page).min(pages.len().saturating_sub(1));
}
}
/// `LecternScreen.pageChanged`: the menu's page data slot.
pub(super) fn remote_lectern_page(&mut self, value: i32) {
if let Some(BookScreen::View {
lectern: Some(_),
pages,
page,
}) = self.book.as_mut()
{
*page = (value.max(0) as usize).min(pages.len().saturating_sub(1));
}
}
/// The server closed its lectern menu; false when none is open.
pub(super) fn remote_lectern_closed(&mut self) -> bool {
if !matches!(
self.book,
Some(BookScreen::View {
lectern: Some(_),
..
})
) {
return false;
}
if let Some(r) = self.remote.as_mut() {
r.menu = None;
r.menu_title = None;
}
self.book = None;
self.capture(true);
true
}
/// `LecternMenu` over the lectern at `key` (the menu engine, for the
/// local player and LAN guests alike): its book and page.
pub(super) fn lectern_menu(&self, key: (i32, i32, i32)) -> Option<Menu> {
let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get(&key) else {
return None;
};
let mut menu = Menu::new(Kind::Lectern);
menu.set_slot(&self.menu_env(), 0, l.book.clone());
menu.data[0] = l.page;
Some(menu)
}
/// The lectern menu's book and page back in the block entity: a new page
/// is `LecternBlock.signalPageChange` (the 2-tick pulse, level event
/// 1043), a book gone `onBookItemRemove` (`resetBookState`).
pub(super) fn lectern_menu_done(&mut self, key: (i32, i32, i32), menu: &Menu) {
let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) else {
return;
};
let (had, before) = (l.book.is_some(), l.page);
l.book = menu.slot(0).cloned();
l.page = menu.data[0];
if had && l.book.is_none() {
self.set_lectern_powered(key, false);
self.set_lectern_property(key, "has_book", false);
self.container_changed(key);
} else if menu.data[0] != before {
self.set_lectern_powered(key, true);
self.lectern_pulses.push((key, 2));
self.level_event_at(1043, [key.0, key.1, key.2], 0);
self.container_changed(key);
}
}
/// The open lectern screen follows its block entity (`LecternScreen`'s
/// menu listener): the page, and closing once the book is gone.
pub(super) fn follow_lectern(&mut self) {
let Some(BookScreen::View {
lectern: Some(key),
page,
pages,
}) = self.book.as_mut()
else {
return;
};
if self.remote.is_some() {
return;
}
match self.world.block_entities.get(key) {
Some(BlockEntity::Lectern(l)) if l.book.is_some() => {
*page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
}
_ => self.close_book(),
}
self.set_lectern_property(key, "has_book", false);
self.container_changed(key);
self.close_book();
}
pub(super) fn book_click(&mut self, size: [u32; 2]) {
let b = HudBatch::new(size);
@@ -537,7 +703,8 @@ impl Game<'_> {
self.close_book();
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
click(self);
self.take_lectern_book(key);
// LecternScreen's Take Book: the menu's button 3.
self.lectern_button(key, 3);
}
} else if inside((w - 200.0) / 2.0, 196.0, 200.0, 20.0) {
click(self);
+68 -58
View File
@@ -1,70 +1,80 @@
//! The cartography table (`CartographyTableMenu`, `CartographyTableScreen`):
//! zooming a map out with paper, cloning it with an empty map, locking it
//! with a glass pane, the post-processing on take (`MapItem.scaleMap`,
//! `lockMap`) and the preview with its error and lock sprites.
//! The cartography table (`CartographyTableMenu` on the menu engine,
//! `CartographyTableScreen`): zooming a map out with paper, cloning it with
//! an empty map, locking it with a glass pane. The engine reads the level's
//! maps through `LevelMaps`; the scaled and locked copies a take makes
//! (`MapItem.scaleMap`, `lockMap`) are registered after the click. The
//! screen draws the preview with its error and lock sprites.
use super::{
Game,
maps::{MapData, map_id},
stations::Station,
};
use horizon_client::{hud::HudBatch, items::ItemStack};
use horizon_client::{hud::HudBatch, items::ItemStack, menu::Maps};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
};
/// The level's maps as a menu sees them (`ContainerLevelAccess`): the
/// states of the maps the click can reach, and the copies it makes.
pub(super) struct LevelMaps {
states: RefCell<HashMap<i32, (bool, u8)>>,
next_id: Cell<i32>,
/// (new id, source id, scaled) for each copy made.
made: RefCell<Vec<(i32, i32, bool)>>,
}
impl Maps for LevelMaps {
fn state(&self, id: i32) -> Option<(bool, u8)> {
self.states.borrow().get(&id).copied()
}
fn derive(&self, id: i32, scale: bool) -> Option<i32> {
let (_, s) = self.state(id)?;
let new = self.next_id.get();
self.next_id.set(new + 1);
let made = if scale {
(false, (s + 1).min(4))
} else {
(true, s)
};
self.states.borrow_mut().insert(new, made);
self.made.borrow_mut().push((new, id, scale));
Some(new)
}
}
impl Game<'_> {
/// `setupResultSlot`.
pub(super) fn cartography_result(&self, s: &Station) -> Option<ItemStack> {
let (map, extra) = (s.inputs[0].as_ref()?, s.inputs[1].as_ref()?);
let data = self.maps.data.get(&map_id(map)?)?;
match &*extra.item {
"minecraft:paper" if !data.locked && data.scale < 4 => Some(ItemStack {
count: 1,
..map.clone()
}),
"minecraft:glass_pane" if !data.locked => Some(ItemStack {
count: 1,
..map.clone()
}),
"minecraft:map" => Some(ItemStack {
count: 2,
..map.clone()
}),
_ => None,
/// The maps of `stacks` (loaded as needed) for a menu over this level.
pub(super) fn level_maps<'s>(
&mut self,
stacks: impl IntoIterator<Item = &'s ItemStack>,
) -> LevelMaps {
let ids: Vec<i32> = stacks.into_iter().filter_map(map_id).collect();
let mut states = HashMap::new();
for id in ids {
if let Some(m) = self.map(id) {
states.insert(id, (m.locked, m.scale));
}
}
LevelMaps {
states: RefCell::new(states),
next_id: Cell::new(self.peek_map_id()),
made: RefCell::new(Vec::new()),
}
}
/// `onCraftedPostProcess` for the taken result: a scaled or locked copy
/// under a new map id. Also spends the inputs' extra item kind check.
pub(super) fn cartography_post(&mut self, mut result: ItemStack) -> ItemStack {
let extra = self
.station
.as_ref()
.and_then(|s| s.inputs[1].as_ref())
.map(|e| e.item.clone());
let Some(id) = map_id(&result) else {
return result;
};
let new = match extra.as_deref() {
Some("minecraft:paper") => self.map(id).map(|m| m.scaled()),
Some("minecraft:glass_pane") => self.map(id).map(|m| m.locked_copy()),
_ => None,
};
if let Some(data) = new {
let new_id = self.new_map_id(data);
result.data_mut().map_id = Some(new_id);
/// The scaled and locked copies a menu made (`level.setMapData`).
pub(super) fn register_made_maps(&mut self, maps: LevelMaps) {
for (id, source, scale) in maps.made.into_inner() {
let Some(data) = self
.map(source)
.map(|m| if scale { m.scaled() } else { m.locked_copy() })
else {
continue;
};
let new = self.new_map_id(data);
debug_assert_eq!(new, id, "map ids follow peek_map_id");
}
result
}
/// The take sound (once per tick).
pub(super) fn cartography_taken(&mut self, pos: [i32; 3]) {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.audio.play(
"minecraft:ui.cartography_table.take_result",
Some(at),
1.0,
1.0,
);
}
/// `CartographyTableScreen.extractBackground` after the background.
pub(super) fn draw_cartography(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) {
+3
View File
@@ -25,6 +25,9 @@ pub(super) struct CombatTracker {
pub(super) last_hurt_mob: Option<(u32, i64)>,
/// The mob whose projectile is hitting the player now.
pub(super) projectile_owner: Option<u32>,
/// The projectile hitting the player now is another player's that
/// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally).
pub(super) refuse_player_hit: bool,
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
/// fire decides whom the blast may hurt.
pub(super) explosion_source: Option<u32>,
+27 -7
View File
@@ -1612,11 +1612,16 @@ impl Game<'_> {
{
return Err(err("commands.summon.failed.peaceful", &[]));
}
let Some(target) = self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)?
else {
return Err(err("commands.summon.failed", &[]));
let before = self.spawned_mark();
let name = match self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)? {
Some(target) => self.target_name(target),
// Spawned as a kind no command target stands for (primed
// TNT, falling blocks, projectiles): its type's name.
None if self.spawned_mark() != before => {
Text::translate(&format!("entity.minecraft.{short}"), &[])
}
None => return Err(err("commands.summon.failed", &[])),
};
let name = self.target_name(target);
self.feedback(Text::translate("commands.summon.success", &[name]));
return Ok(1);
}
@@ -1669,16 +1674,31 @@ impl Game<'_> {
}
// SummonCommand.createEntity: any other type from an empty compound.
_ => {
let Some(target) = self.summon_with_nbt(&kind, pos, "{}")? else {
return Err(err("commands.summon.failed", &[]));
let before = self.spawned_mark();
name = match self.summon_with_nbt(&kind, pos, "{}")? {
Some(target) => self.target_name(target),
// Spawned as a kind no command target stands for
// (primed TNT, falling blocks, projectiles).
None if self.spawned_mark() != before => {
Text::translate(&format!("entity.minecraft.{short}"), &[])
}
None => return Err(err("commands.summon.failed", &[])),
};
name = self.target_name(target);
}
}
}
self.feedback(Text::translate("commands.summon.success", &[name]));
Ok(1)
}
/// What changes when an entity spawns, kinds that take their id only
/// when first tracked (primed TNT, falling blocks, projectiles)
/// included: a summon compares it before and after.
fn spawned_mark(&self) -> (u32, usize) {
(
self.next_entity,
self.tnts.len() + self.falling.len() + self.creatures.projectiles.len(),
)
}
/// BlockStateArgument -> registry state.
pub(super) fn block_state(&self, b: &BlockInput) -> R<BlockStateId> {
let state = horizon_world::chunk::BlockState {
+76 -4
View File
@@ -24,6 +24,7 @@ const HELP: &[&str] = &[
"time TICKS set the time of day",
"summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)",
"mobs [RADIUS] list mobs near the player with their AI state",
"hurtlog the hurts taken and melee attacks made since the last call, per player (host and guests)",
"fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of loaded blocks",
"resume leave the pause menu",
"screenshot PATH write the next frame as PNG",
@@ -469,6 +470,10 @@ impl Game<'_> {
let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?;
Ok(Some(self.control_mobs(radius)))
}
"hurtlog" => {
self.require_world()?;
Ok(Some(self.control_hurt_log()))
}
"resume" => {
if self.screen == Screen::Paused {
self.screen = Screen::Playing;
@@ -518,13 +523,22 @@ impl Game<'_> {
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
// The anvil's rename box.
Screen::Inventory
if self
.station
.as_ref()
.is_some_and(|s| s.kind == super::stations::Kind::Anvil) =>
{
self.station_text(Some(text), false)
}
Screen::Creative if self.creative_screen.tab().search => {
// As typed: replaces a selected query, keeps the length limit.
self.creative_search_edit(Some(text), false)
}
_ => {
return Err(
"type needs the chat screen (key t tap), the language search, the creative search or World Options".into(),
"type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(),
);
}
}
@@ -661,7 +675,7 @@ impl Game<'_> {
"dragon-hurt" => {
// Test hook: damage the dragon's head as the player would.
let amount: f32 = arg(1)?.parse()?;
self.hit_special(super::dragon::SPECIAL, amount, true);
self.hit_special(super::dragon::SPECIAL, amount, true, false);
ok()
}
"quit" => {
@@ -726,6 +740,54 @@ impl Game<'_> {
}
}
/// The hurts and melee attacks each player logged since the last call
/// (`PlayerMotion::hurt_log`, `attack_log`), taken out.
fn control_hurt_log(&mut self) -> Value {
fn drain(
name: &str,
hurt_log: &mut Vec<horizon_client::health::HurtRecord>,
attack_log: &mut Vec<horizon_client::health::AttackRecord>,
) -> Value {
let hurts: Vec<Value> = hurt_log
.drain(..)
.map(|r| {
json!({
"t": r.game_time, "source": r.source, "amount": r.amount,
"blocked": r.blocked, "taken": r.taken, "hurt": r.hurt,
"armor": r.armor, "toughness": r.toughness, "health": r.health,
"fire_ticks": r.fire_ticks, "knockback": r.knockback,
})
})
.collect();
let attacks: Vec<Value> = attack_log
.drain(..)
.map(|r| {
json!({
"t": r.game_time, "target": r.target, "id": r.id, "killed": r.killed, "amount": r.amount,
"scale": r.scale, "crit": r.crit, "landed": r.landed, "dealt": r.dealt,
})
})
.collect();
json!({ "name": name, "hurts": hurts, "attacks": attacks })
}
let mut players = Vec::new();
if let Some(p) = self.player.as_mut() {
players.push(drain("host", &mut p.hurt_log, &mut p.attack_log));
}
if let Some(host) = self.lan.as_mut() {
for g in &mut host.hub.guests {
let name = g.name.clone();
if let Some(m) = g.motion.as_mut() {
players.push(drain(&name, &mut m.hurt_log, &mut m.attack_log));
} else if let Some((mut hurts, mut attacks)) = g.logs_kept.take() {
// Dead, not yet respawned: what its last body logged.
players.push(drain(&name, &mut hurts, &mut attacks));
}
}
}
json!({ "ok": true, "players": players })
}
fn control_status(&self) -> Value {
let player = self.player.as_ref().map(|p| {
json!({
@@ -788,6 +850,12 @@ impl Game<'_> {
"pending_observations": self.lod_observe.len(),
"refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()),
});
// The other players' cracks this client draws (LevelRenderer.destroyingBlocks).
let destroying: Vec<_> = self
.destroying
.iter()
.map(|(id, (pos, stage, _))| json!({ "id": id, "pos": pos, "stage": stage }))
.collect();
let mut status = json!({
"screen": self.screen_name(),
"debug": {
@@ -820,14 +888,16 @@ impl Game<'_> {
"tridents": self.tridents.len(),
"rockets": self.rockets.len(),
"fight": self.dragon_status(),
"carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::<Vec<_>>(),
// A client of a server (single player's server thread) knows the
// carts it was sent.
"carts": self.remote_carts().unwrap_or_else(|| self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::<Vec<_>>()),
"riding": self.riding,
"using": self.using,
"render_distance": self.streaming.radius,
"chunks": self.world.chunks.len(),
"mobs": self.mobs.len(),
"block_entities": self.world.block_entities.len(),
"pending_chunks": self.streaming.pending() + self.pending_uploads.len(),
"pending_chunks": self.streaming.pending() + self.pending_uploads.len() + self.remote_backlog(),
"generated_chunks": self.streaming.generated_total,
"meshed_sections": self.streaming.meshed_total,
"streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::<serde_json::Map<_, _>>(),
@@ -851,7 +921,9 @@ impl Game<'_> {
status["lod"]["target_tiles"] = target.into();
status["lod"]["sampled_target_tiles"] = sampled.into();
status["pending_uploads"] = self.pending_uploads.len().into();
status["destroying"] = json!(destroying);
status["physical_keys"] = json!(physical_keys);
status["heard"] = json!(self.audio.heard);
// Boats, minecarts, armor stands, item frames and paintings.
status["objects"] = json!(self.objects_status());
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
+132 -26
View File
@@ -3,6 +3,7 @@
//! breeding, conversions, drops), projectiles, player interactions
//! (feeding, shearing, milking, spawn eggs, throwing) and rendering.
use super::{Dim, Game, view_vector};
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
Result,
arrows::EntityHit,
@@ -389,6 +390,7 @@ impl Game<'_> {
player,
others,
others_grid: None,
others_index: None,
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
game_time: self.world.game_time,
day_time: self.world.day_time,
@@ -401,7 +403,7 @@ impl Game<'_> {
end: self.dim == Dim::End,
world_seed: self.level.seed,
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
teams: self.mob_teams(),
teams: std::sync::Arc::new(self.mob_teams()),
items: Some(self.res.items()),
difficulty: self.local_difficulty(
self.player
@@ -502,9 +504,22 @@ impl Game<'_> {
let mut keep = Vec::with_capacity(mobs.len());
let mut grid =
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
// All but the snapshot is the same for every mob of the tick, so
// build it once: the player view and the teams scan every UUID.
let base = self.mob_world_base(&[]);
// Each mob keeps its snapshot slot all tick; the first slot of an
// id answers, as a scan would.
let mut index = horizon_client::fast_hash::FxHashMap::<u32, u32>::default();
for (i, s) in snapshot.iter().enumerate() {
index.entry(s.id).or_insert(i as u32);
}
for i in 0..mobs.len() {
let mut w = self.mob_world_base(&snapshot);
w.others_grid = Some(&grid);
let mut w = MobWorld {
others: &snapshot,
others_grid: Some(&grid),
others_index: Some(&index),
..base.clone()
};
let m = &mut mobs[i];
w.nearest_player = super::natural_spawning::nearest_player(
&players,
@@ -588,7 +603,11 @@ impl Game<'_> {
if let Some(host) = self.lan.as_mut()
&& !guests.is_empty()
{
bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id));
// A set: a scan of every mob for each binding is quadratic, and a
// server's loaded mobs run into the thousands.
let live: horizon_client::fast_hash::FxHashSet<u32> =
mobs.iter().map(|m| m.id).collect();
bindings.retain(|id, _| live.contains(id));
host.mob_players = bindings;
}
self.mobs.append(&mut mobs);
@@ -622,7 +641,8 @@ impl Game<'_> {
}
/// LivingEntity.die / dropAllDeathLoot.
fn mob_died(&mut self, m: &Mob) {
let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0;
let killer = self.last_hurt_by_player.remove(&m.id);
let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0;
let mut dying = m.clone();
// LivingEntity.die: the death is heard, and a sculk catalyst nearby
// takes the experience (before the loot is dropped).
@@ -636,11 +656,22 @@ impl Game<'_> {
}
});
if by_player {
self.stats.add("killed", &m.kind.id, 1);
self.stats.custom("mob_kills", 1);
self.score_player_killed(super::commands::Target::Mob(m.id));
let view = self.mob_entity(m);
self.trigger_entity("minecraft:player_killed_entity", "entity", &view);
// A guest's kill is theirs: their statistics, scores and
// advancements (LivingEntity.die credits lastHurtByPlayer).
let guest = killer.flatten().filter(|_| self.lan_acting.is_none());
let credited = guest.is_some_and(|conn| {
let Some(mut host) = self.lan.take() else {
return false;
};
let done = self
.as_guest(&mut host, conn, |g| g.credit_kill(m))
.is_some();
self.lan = Some(host);
done
});
if !credited {
self.credit_kill(m);
}
}
self.score_entity_removed(m.id);
self.raider_died(m, by_player);
@@ -675,6 +706,15 @@ impl Game<'_> {
}
}
}
/// The killer's side of a mob's death: `ServerPlayer.awardKillScore`'s
/// statistics and scores, and the `player_killed_entity` trigger.
fn credit_kill(&mut self, m: &Mob) {
self.stats.add("killed", &m.kind.id, 1);
self.stats.custom("mob_kills", 1);
self.score_player_killed(super::commands::Target::Mob(m.id));
let view = self.mob_entity(m);
self.trigger_entity("minecraft:player_killed_entity", "entity", &view);
}
/// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the
/// world's random sequence, equipment by drop chance, species extras and
/// the experience orbs, spawned in order.
@@ -1393,7 +1433,8 @@ impl Game<'_> {
from: [f64; 3],
damage_type: &str,
) -> bool {
if self.creative {
// ServerPlayer.canHarmPlayer refused another player's projectile.
if self.creative || self.combat.refuse_player_hit {
return false;
}
let projectile = self
@@ -1442,6 +1483,11 @@ impl Game<'_> {
{
let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z);
self.knock_back_player(f64::from(0.4_f32), xd, zd);
if let Some(p) = self.player.as_mut()
&& let Some(r) = p.hurt_log.last_mut()
{
r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]);
}
self.hurt_armor(amount);
self.thorns(from);
}
@@ -1626,14 +1672,30 @@ impl Game<'_> {
w: &w,
targets: targets_guests,
};
let guest_entities = self.lan_guest_entities();
projectiles.retain_mut(|p| {
let mob_shot = !matches!(p.owner, Some(Who::Player));
let (keep, hit) = match (p.arrow.is_some(), mob_shot) {
// A player's arrows, snowballs and eggs meet every player; a
// guest's flies from that guest (Projectile.getOwner), not
// from the host, until it has left them.
let pvp = !mob_shot && super::lan_pvp::meets_players(&p.kind);
let shooter = p
.guest
.filter(|_| pvp)
.and_then(|c| guest_entities.iter().find(|(g, _)| *g == c))
.map(|&(_, id)| Who::Mob(id));
if shooter.is_some() {
p.owner = shooter;
}
let (keep, hit) = match (p.arrow.is_some(), mob_shot || pvp) {
(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 shooter.is_some() {
p.owner = Some(Who::Player);
}
if let Some(a) = p.arrow.as_mut() {
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
}
@@ -1685,6 +1747,11 @@ impl Game<'_> {
}
self.creatures.projectiles.append(&mut projectiles);
for (p, hit) in hits {
// A player's arrow on another player lands as the victim's hurt.
if let Some(victim) = self.projectile_pvp_victim(&p, hit) {
self.projectile_hits_player(&p, hit, victim)?;
continue;
}
// A guest's projectile lands as theirs: a pearl takes them, what
// it hurts answers to them. One hitting the host (`Who::Player`
// here) stays the host's hit.
@@ -1879,12 +1946,30 @@ impl Game<'_> {
} = hit
&& id >= super::dragon::SPECIAL
{
let by_player = p.owner == Some(Who::Player);
if let ProjectileKind::Arrow { .. } = p.kind {
// AbstractArrow.onHitEntity: spent if the part or crystal took
// it, else turned back (a perched dragon sets it alight first).
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
let outcome = match self.hit_special(id, amount, by_player, true) {
super::dragon::Hurt::Landed { .. } => EntityHit::Hurt,
super::dragon::Hurt::Refused => EntityHit::Refused,
super::dragon::Hurt::Shrugged => {
if let Some(a) = arrow.arrow.as_mut() {
a.ignite_for_seconds(1.0);
}
EntityHit::Refused
}
};
self.finish_arrow_hit(arrow, outcome);
return Ok(());
}
let amount = match p.kind {
ProjectileKind::Arrow { .. } => p.arrow_damage(&mut self.world.random),
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => 6.0,
_ => 0.0,
};
self.hit_special(id, amount, p.owner == Some(Who::Player));
self.hit_special(id, amount, by_player, false);
return Ok(());
}
if let (
@@ -1950,7 +2035,7 @@ impl Game<'_> {
.find(|m| m.id == id)
.is_some_and(|m| m.damage(amount, source));
if p.owner == Some(Who::Player) {
self.last_hurt_by_player.insert(id);
self.last_hurt_by_player.insert(id, self.lan_acting);
}
hurt
}
@@ -2040,15 +2125,22 @@ impl Game<'_> {
let from = pl.position;
self.spawn_mob("minecraft:endermite", [from.x, from.y, from.z], false);
}
// To where the pearl started its last tick (oldPosition).
let to = p.previous;
if let Some(pl) = self.player.as_mut() {
pl.position = at;
pl.position = to;
pl.velocity = Vec3::ZERO;
pl.fall_distance = 0.0;
pl.teleported = true;
}
self.previous_position = at;
self.previous_position = to;
self.hurt_player_by("minecraft:ender_pearl", 5.0);
self.audio
.play("minecraft:entity.player.teleport", Some(atp), 1.0, 1.0);
self.audio.play(
"minecraft:entity.player.teleport",
Some([to.x, to.y, to.z]),
1.0,
1.0,
);
}
}
(ProjectileKind::SmallFireball, hit) => match hit {
@@ -2075,15 +2167,21 @@ impl Game<'_> {
}
},
Hit::Block { pos, face, .. } => {
// SmallFireball.onHitBlock: a mob's only with mobGriefing;
// BaseFireBlock.getState placed with updates (the fire
// ticks, ages and goes out where it can't stay).
let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]];
if self
.res
.facts()
.is_air(self.world.block(fire[0], fire[1], fire[2]))
&& let Some(state) =
self.pack.assets.registry.default_state("minecraft:fire")
let mob = matches!(p.owner, Some(Who::Mob(_)));
if (!mob || self.ui.rules.bool("mob_griefing"))
&& self
.res
.facts()
.is_air(self.world.block(fire[0], fire[1], fire[2]))
{
self.world.set(fire[0], fire[1], fire[2], state)?;
let at = BlockPos::new(fire[0], fire[1], fire[2]);
let state =
self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at));
self.level_set(fire, state)?;
}
}
Hit::None => {}
@@ -3035,6 +3133,14 @@ impl Game<'_> {
}
continue;
}
if let Some(stack) = a.potion_item() {
let owner = super::item_draw::owner_at(at, 0.0, "minecraft:splash_potion");
let state = self.resolve_item(&stack, DisplayContext::Ground, Some(&owner), 0);
let pose = glam::Mat4::from_translation(c)
* glam::Mat4::from_quat(self.camera_orientation());
self.submit_item_world(&state, pose, packed, out);
continue;
}
let Some(name) = a.item_sprite() else {
continue;
};
+155
View File
@@ -0,0 +1,155 @@
//! A player's blow at a ghast's fireball or a wind charge
//! (`#minecraft:redirectable_projectile`): `Player.attack` turns it with
//! `ProjectileDeflection.AIM_DEFLECT` instead of hurting anything. It flies on
//! along the player's view and is the player's now (`Projectile.deflect`
//! sets the owner), so a ghast it meets dies of it (`Ghast.isReflectedFireball`).
use super::{Game, ray_box, view_vector};
use horizon_client::{
mobs::Who,
projectiles::{Projectile, ProjectileKind},
};
use horizon_core::geometry::{Aabb, Vec3};
/// `AbstractHurtingProjectile.getPickRadius`: the crosshair finds it a block
/// round its box.
const PICK_RADIUS: f64 = 1.0;
/// `#minecraft:redirectable_projectile`: a ghast's fireball and both wind charges.
pub(super) fn redirectable(p: &Projectile) -> bool {
!p.stuck
&& matches!(
p.kind,
ProjectileKind::LargeFireball { .. }
| ProjectileKind::WindCharge
| ProjectileKind::BreezeWindCharge
)
}
/// Its box for the crosshair: the entity's (a fireball 1 x 1, a wind charge
/// 0.3125, from its feet up) grown by the pick radius.
fn pick_box(p: &Projectile) -> Aabb {
let size = match p.kind {
ProjectileKind::LargeFireball { .. } => 1.0,
_ => 0.3125,
};
let half = size / 2.0 + PICK_RADIUS;
Aabb::new(
Vec3::new(
p.position.x - half,
p.position.y - PICK_RADIUS,
p.position.z - half,
),
Vec3::new(
p.position.x + half,
p.position.y + size + PICK_RADIUS,
p.position.z + half,
),
)
}
impl Game<'_> {
/// The redirectable projectile under the crosshair within the attack
/// reach, and how far along the view it is.
pub(super) fn redirectable_hit(&self) -> Option<(usize, f64)> {
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let reach: f64 = if self.creative { 5.0 } else { 3.0 };
self.creatures
.projectiles
.iter()
.enumerate()
.filter(|(_, p)| redirectable(p))
.filter_map(|(i, p)| ray_box(eye, dir, reach, pick_box(p)).map(|t| (i, t)))
.min_by(|a, b| a.1.total_cmp(&b.1))
}
/// `Player.attack` on a redirectable projectile nearer than any mob or
/// block in view: `AIM_DEFLECT` (its movement the unit view vector), the
/// player its owner, its acceleration power back to 0.1
/// (`onDeflection` by an attack), and the no-damage sound. True when a
/// projectile was turned.
pub(super) fn attack_redirectable(&mut self) -> bool {
let Some((i, t)) = self.redirectable_hit() else {
return false;
};
if self.mob_hit().is_some_and(|(_, d)| d < t) {
return false;
}
if let (Some(hit), Some(eye)) = (self.pick(), self.eye_position()) {
let d = (0..3)
.map(|a| (hit.point[a] - eye[a]).powi(2))
.sum::<f64>()
.sqrt();
if d < t {
return false;
}
}
self.deflect(i);
true
}
/// `Player.canInteractWithEntity(box, 3.0)` as the server checks an
/// attack packet: the projectile's box within the reach plus 3 of the eyes.
pub(super) fn within_interaction_range(&self, i: usize) -> bool {
let (Some(eye), Some(p)) = (self.eye_position(), self.creatures.projectiles.get(i)) else {
return false;
};
let b = pick_box(p);
let (lo, hi) = (b.min_position(), b.max_position());
let (lo, hi) = (
[lo.x + PICK_RADIUS, lo.y + PICK_RADIUS, lo.z + PICK_RADIUS],
[hi.x - PICK_RADIUS, hi.y - PICK_RADIUS, hi.z - PICK_RADIUS],
);
let d2: f64 = (0..3)
.map(|a| (eye[a] - eye[a].clamp(lo[a], hi[a])).powi(2))
.sum();
let range = if self.creative { 5.0 } else { 3.0 } + 3.0;
d2 < range * range
}
/// `Projectile.deflect(AIM_DEFLECT, player, player, true)`.
pub(super) fn deflect(&mut self, i: usize) {
let dir = view_vector(self.yaw, self.pitch);
let guest = self.lan_acting;
let p = &mut self.creatures.projectiles[i];
p.velocity = Vec3::new(dir[0], dir[1], dir[2]);
p.yaw = dir[0].atan2(dir[2]).to_degrees() as f32;
p.pitch = dir[1].atan2(dir[0].hypot(dir[2])).to_degrees() as f32;
p.owner = Some(Who::Player);
// On a server, the guest who struck it (their projectile now).
p.guest = guest;
// Not into the one who turned it on its way out.
p.left_owner = false;
self.reset_attack_strength();
self.swing_arm();
let from = self
.player
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z]);
self.audio
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_ghast_fireballs_and_wind_charges_are_redirectable() {
let at = Vec3::new(0.0, 64.0, 0.0);
let large = Projectile::fireball(
ProjectileKind::LargeFireball { power: 1 },
at,
None,
[1.0, 0.0, 0.0],
);
let small = Projectile::fireball(ProjectileKind::SmallFireball, at, None, [1.0, 0.0, 0.0]);
assert!(redirectable(&large));
assert!(!redirectable(&small));
// The pick box: a block round the fireball's 1 x 1 box.
let b = pick_box(&large);
assert_eq!(b.min_position().x, -1.5);
assert_eq!(b.max_position().y, 66.0);
}
}
+5 -1
View File
@@ -317,7 +317,11 @@ impl Game<'_> {
.cloned()
}
/// The same block with other properties (`withProperty`).
fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option<BlockStateId> {
pub(super) fn with_props(
&self,
state: BlockStateId,
props: &[(&str, &str)],
) -> Option<BlockStateId> {
let mut s = self.pack.assets.registry.state(state)?.clone();
for (k, v) in props {
s.properties.insert((*k).to_owned(), (*v).to_owned());
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,67 @@
//! Horizon Extras' dynamic lights (`horizon_client::dynamic_light`): the light sources near the
//! camera this frame. Nothing is gathered while the extra is off.
use super::{Game, shield};
use glam::DVec3;
use horizon_client::dynamic_light::{self, BURNING, Luminance, Source};
impl Game<'_> {
/// Fills `dynamic_lights` for the frame: the player's and mobs' held items and fire, and
/// glowing dropped items, the nearest [`dynamic_light::MAX`] of them.
pub(super) fn gather_dynamic_lights(&mut self, camera: DVec3, alpha: f64) {
let mut out = std::mem::take(&mut self.dynamic_lights);
out.clear();
if !self.settings.extras.dynamic_lights {
self.dynamic_lights = out;
return;
}
if self.luminance.is_none() {
self.luminance = Some(Luminance::new(self.res.facts(), self.pack.assets.registry));
}
let lum = self.luminance.as_ref().expect("built above");
let held = |item: Option<&str>| item.map_or(0, |i| lum.of(i));
let mut sources = Vec::new();
if let Some(p) = &self.player
&& !p.spectator
{
let feet = self
.previous_position
.lerp(p.position, self.clock.camera_fraction());
let level = held(self.stack_in(self.selected).map(|s| &*s.item))
.max(held(self.stack_in(shield::OFFHAND_SLOT).map(|s| &*s.item)))
.max(if p.fire_ticks > 0 { BURNING } else { 0 });
// About where the hands are.
sources.push(Source {
at: DVec3::new(feet.x, feet.y + 1.2, feet.z),
level,
});
}
for m in self.mobs.iter().filter(|m| !m.removed) {
let level = held(m.extra.main_hand.as_deref())
.max(held(m.extra.off_hand.as_deref()))
.max(if m.fire_ticks > 0 { BURNING } else { 0 });
if level == 0 {
continue;
}
let at = m.previous.lerp(m.position, alpha);
sources.push(Source {
at: DVec3::new(at.x, at.y + f64::from(m.height()) * 0.6, at.z),
level,
});
}
for item in &self.dropped {
let level = lum
.of(&item.stack.item)
.max(if item.fire_ticks > 0 { BURNING } else { 0 });
if level == 0 {
continue;
}
let at = item.previous.lerp(item.position, alpha);
sources.push(Source {
at: DVec3::new(at.x, at.y + 0.25, at.z),
level,
});
}
dynamic_light::select(&sources, camera, &mut out);
self.dynamic_lights = out;
}
}
+1
View File
@@ -350,6 +350,7 @@ impl Game<'_> {
self.tick_fight();
self.tick_dragon_fireballs();
}
self.tick_crystals();
self.tick_eyes();
if self.dim == Dim::End {
self.end.flash.tick(self.world.game_time);
+112 -50
View File
@@ -226,6 +226,102 @@ impl Game<'_> {
}
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT);
/// the player takes `damage_type`.
/// `ServerExplosion.hurtEntities` for the player: damage scaled by
/// distance and exposure, through a raised shield (`hurtServer` blocks
/// explosions like any attack from where the blast is), then the push
/// (less with explosion knockback resistance; none for spectators or a
/// creative player flying).
pub(super) fn explosion_hurt_player(
&mut self,
center: [f64; 3],
radius: f32,
damage_type: &str,
exploding: Option<u32>,
) {
let diameter = f64::from(radius * 2.0);
// Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per level and
// piece, so two Blast Protection IV pieces cancel it).
let resistance = self
.player
.as_mut()
.and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok())
.unwrap_or(0.0);
let Some(p) = self.player.as_ref() else {
return;
};
let feet = [p.position.x, p.position.y, p.position.z];
let dist = ((feet[0] - center[0]).powi(2)
+ (feet[1] - center[1]).powi(2)
+ (feet[2] - center[2]).powi(2))
.sqrt()
/ diameter;
if dist > 1.0 || p.health.dead_or_dying() {
return;
}
let w = f64::from(p.dimensions.width) / 2.0;
let h = f64::from(p.dimensions.height);
let eye = [
feet[0],
feet[1] + f64::from(p.dimensions.eye_height),
feet[2],
];
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let pow = (1.0 - dist) * f64::from(exposure);
let amount = ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32;
let d = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]];
let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let dir = if l < 1.0e-4 {
[0.0; 3]
} else {
[d[0] / l, d[1] / l, d[2] / l]
};
let power = pow * (1.0 - resistance);
// `source.doTeamsAllowDamage(entity)`.
let hurtable = exploding.is_none_or(|id| {
horizon_client::scoreboard::teams_allow_damage(self.mob_team(id), self.player_team())
});
let blocking = self.player_blocking(Some(center), damage_type, false);
let raised = blocking.is_some();
let (creative, spectator) = (self.creative, self.spectator());
let flying = self.player.as_ref().is_some_and(|p| p.flying);
let mut outcome = horizon_client::health::BlockOutcome::default();
if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(damage_type)
{
// Creative players are invulnerable to explosions.
if !creative
&& !spectator
&& hurtable
&& let Ok(o) = p.hurt_blocking(
&self.motion.health,
self.world.health_rules,
id,
amount,
blocking,
)
{
outcome = o;
}
if !spectator && !(creative && flying) {
p.velocity = Vec3::new(
p.velocity.x + dir[0] * power,
p.velocity.y + dir[1] * power,
p.velocity.z + dir[2] * power,
);
}
}
if outcome.hurt && !creative {
self.hurt_armor(amount);
}
if raised {
self.after_block(outcome, amount, None, false);
}
}
fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) {
if radius < 1.0e-5 {
return;
@@ -261,57 +357,23 @@ impl Game<'_> {
horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim)
})
};
let player_hurtable = teams_allow(self, self.player_team());
// Player.
if let Some(p) = self.player.as_ref() {
let feet = [p.position.x, p.position.y, p.position.z];
let dist = distance(feet) / diameter;
if dist <= 1.0 && !p.health.dead_or_dying() {
let w = f64::from(p.dimensions.width) / 2.0;
let h = f64::from(p.dimensions.height);
let eye = [
feet[0],
feet[1] + f64::from(p.dimensions.eye_height),
feet[2],
];
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let amount = damage(dist, exposure);
let dir = direction(eye);
let mut hurt = false;
let creative = self.creative;
if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(damage_type)
{
// Creative players are invulnerable to explosions.
if !creative && player_hurtable {
hurt = p
.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false);
}
// Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per
// level and piece, so two Blast Protection IV pieces cancel it).
let resistance = p
.attribute("minecraft:explosion_knockback_resistance")
.unwrap_or(0.0);
let power = (1.0 - dist) * f64::from(exposure) * (1.0 - resistance);
// `hitPlayers` skips creative players who are flying: the
// client gets no knockback in the explode packet.
if !(creative && p.flying) {
p.velocity = Vec3::new(
p.velocity.x + dir[0] * power,
p.velocity.y + dir[1] * power,
p.velocity.z + dir[2] * power,
);
}
}
if hurt && !self.creative {
self.hurt_armor(amount);
}
// The player, then every other player in the level (LAN guests),
// each swapped in as the player.
self.explosion_hurt_player(center, radius, damage_type, exploding);
if let Some(mut host) = self.lan.take() {
let guests: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
.map(|g| g.conn)
.collect();
for conn in guests {
self.guest_hit_by(&mut host, conn, |g| {
g.explosion_hurt_player(center, radius, damage_type, exploding);
});
}
self.lan = Some(host);
}
// Mobs.
let mut mobs = std::mem::take(&mut self.mobs);
+1
View File
@@ -156,6 +156,7 @@ impl Game<'_> {
|| before(self.dragon_hit().map(|h| h.1))
|| before(self.mob_hit().map(|h| h.1))
|| before(self.guest_hit().map(|h| h.1))
|| before(self.redirectable_hit().map(|h| h.1))
}
/// `LocalPlayer.isHandsBusy`: paddling a boat.
fn hands_busy(&self) -> bool {
+3 -3
View File
@@ -6,9 +6,9 @@
//! the world's options) with [`Integrated::call`], as vanilla's client calls
//! into its `IntegratedServer`.
//!
//! 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.
//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs
//! the world in the frame instead (the escape hatch while the network
//! player's side catches up with the in-frame one).
use super::{
Game, Options, PackResources, Resources, UiResources,
lan::{LanSettings, Owner},
+75 -78
View File
@@ -10,7 +10,7 @@ use horizon_client::{
self, Lan, MAX_PLAYERS, NetConfig,
chunks::ChunkEncoder,
data::SyncData,
entity::EntityState,
entity::{EntityState, States},
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
@@ -44,6 +44,8 @@ pub(super) struct LanHost {
pub host_entity: i32,
/// The host's swings the guests were told of (`Game::swings_started`).
pub host_swings: u32,
/// The host's crack the guests were told of: the block and its stage.
pub host_crack: Option<([i32; 3], i32)>,
pub host_uuid: u128,
/// The host's profile name (the account's, or the offline name).
pub host_name: String,
@@ -59,13 +61,17 @@ pub(super) struct LanHost {
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
pub owner: Option<Owner>,
/// The players' locator bars (game/lan_waypoints.rs), and the guests who
/// are dead, whose respawn replaces their waypoint.
pub waypoints: lan::waypoints::Waypoints,
/// The players' locator bars, one waypoint manager per level by
/// dimension id (game/lan_waypoints.rs), and the guests who are dead,
/// whose respawn replaces their waypoint.
pub waypoints: std::collections::HashMap<String, lan::waypoints::Waypoints>,
pub waypoint_dead: std::collections::HashSet<u128>,
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec<super::lan_actions::GuestCommand>,
/// The entities the guests track, described again every tick
/// (`lan_entities`) over last tick's states.
states: lan::entity::States,
}
/// The player who owns an integrated server's world: a guest whose state is
@@ -133,8 +139,7 @@ fn baby_index(kind: &str) -> Option<u8> {
/// A mob's synched data as ServerEntity sends it (only the values that differ
/// from the defaults the client constructs), with vanilla's entry indices:
/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses.
fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
let mut meta = Vec::new();
fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
let kind = m.kind.id.as_str();
if m.fire_ticks > 0 {
meta.push((0, serializer::BYTE, Value::Byte(1)));
@@ -277,14 +282,16 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
}
_ => {}
}
meta
}
/// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand,
/// off hand, feet, legs, chest, head, body, saddle).
fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option<horizon_protocol::item::Stack>)> {
fn mob_equipment(
m: &Mob,
hub: &mut Hub,
out: &mut Vec<(u8, Option<horizon_protocol::item::Stack>)>,
) {
let e = &m.extra;
let mut out = Vec::new();
let slots = [
(0u8, &e.main_hand),
(1, &e.off_hand),
@@ -313,7 +320,6 @@ fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option<horizon_protocol::it
});
out.push((7, hub.stack(&Some(stack))));
}
out
}
pub const HELP: &[&str] = &[
@@ -395,6 +401,8 @@ impl Game<'_> {
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// Whether the host draws this guest lying in a bed.
"model_lying": h.models.get(&g.conn).map(|m| m.extra.ints[1] != 0),
// The armour the host draws on this guest, head to feet.
"model_armor": h.models.get(&g.conn).map(|m| {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
@@ -519,6 +527,7 @@ impl Game<'_> {
settings: LanSettings { port, ..settings },
host_entity,
host_swings: self.swings_started,
host_crack: None,
host_uuid,
host_name: self.options.player_name(),
models: HashMap::new(),
@@ -531,6 +540,7 @@ impl Game<'_> {
waypoints: Default::default(),
waypoint_dead: Default::default(),
commands: Vec::new(),
states: Default::default(),
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -734,76 +744,44 @@ impl Game<'_> {
equipment,
health: p.health.health(),
attributes: horizon_client::lan::attributes::syncable(&p.attributes),
living_flags: living_flags(self.using),
// Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack).
living_flags: living_flags(self.using)
| if p.auto_spin_attack_ticks > 0 { 4 } else { 0 },
bed: self.sleeping,
})
}
/// The entities guests track: mobs, items and the rest (game/lan_entities.rs).
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub) -> Vec<EntityState> {
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len());
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
out.clear();
for m in self.mobs.iter().filter(|m| !m.removed) {
let kind = m.kind.id.as_str();
let meta = mob_meta(m, hub);
let equipment = mob_equipment(m, hub);
let attributes = self.mob_attributes(m);
let (yaw, pitch) = (m.yaw, m.head_pitch);
out.push(EntityState {
id: m.id as i32,
uuid: entity_uuid(m.id),
kind: kind.to_owned(),
position: [m.position.x, m.position.y, m.position.z],
yaw,
pitch,
head_yaw: m.head_yaw,
on_ground: m.on_ground,
velocity: [m.velocity.x, m.velocity.y, m.velocity.z],
data: 0,
meta,
equipment,
attributes,
precise: false,
});
let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str());
e.position = [m.position.x, m.position.y, m.position.z];
(e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw);
e.on_ground = m.on_ground;
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
mob_meta(m, hub, &mut e.meta);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
}
for d in &self.dropped {
let stack = hub.stack(&Some(d.stack.clone()));
out.push(EntityState {
id: d.id as i32,
uuid: entity_uuid(d.id),
kind: "minecraft:item".to_owned(),
position: [d.position.x, d.position.y, d.position.z],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: d.on_ground,
velocity: [d.velocity.x, d.velocity.y, d.velocity.z],
data: 0,
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
});
let e = out.add(d.id as i32, entity_uuid(d.id), "minecraft:item");
e.position = [d.position.x, d.position.y, d.position.z];
e.on_ground = d.on_ground;
e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z];
e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack)));
}
for o in &self.orbs {
out.push(EntityState {
id: o.id as i32,
uuid: entity_uuid(o.id),
kind: "minecraft:experience_orb".to_owned(),
position: [o.position.x, o.position.y, o.position.z],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: o.on_ground,
velocity: [o.velocity.x, o.velocity.y, o.velocity.z],
data: 0,
// ExperienceOrb.DATA_VALUE.
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
});
let e = out.add(o.id as i32, entity_uuid(o.id), "minecraft:experience_orb");
e.position = [o.position.x, o.position.y, o.position.z];
e.on_ground = o.on_ground;
e.velocity = [o.velocity.x, o.velocity.y, o.velocity.z];
// ExperienceOrb.DATA_VALUE.
e.meta
.push((8, serializer::INT, Value::Int(o.value as i32)));
}
self.lan_object_states(host_entity, hub, &mut out);
out
self.lan_object_states(host_entity, hub, out);
}
/// Run the hub for this tick and apply what the guests did.
@@ -825,21 +803,23 @@ impl Game<'_> {
// A dedicated server runs the hub without a host player.
if state.is_some() || host.hub.config.dedicated {
let has_guests = !host.hub.guests.is_empty();
let entities = if has_guests {
let mut states = std::mem::take(&mut host.states);
if has_guests {
let host_entity = state.as_ref().map(|s| s.entity_id);
self.lan_assign_ids();
self.lan_riding(host_entity, &mut host.hub.riding);
self.lan_entities(host_entity, &mut host.hub)
self.lan_entities(host_entity, &mut host.hub, &mut states);
} else {
Vec::new()
};
states.clear();
}
let entities = states.as_slice();
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
let clock_rate = self.network_clock_rate();
let mut ctx = TickCtx {
world: &mut self.world,
host: state.as_ref(),
entities: &entities,
entities,
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
@@ -880,7 +860,7 @@ impl Game<'_> {
self.lan_log_event(event);
}
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn);
self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn);
if self.options.dedicated.is_some()
&& let Some(g) = host.hub.guest(conn)
{
@@ -945,6 +925,7 @@ impl Game<'_> {
}
}
}
host.states = states;
}
self.lan_flush_effects(&mut host);
self.tick_guests(&mut host);
@@ -1004,15 +985,15 @@ impl Game<'_> {
g.dimension = in_place;
}
self.load_guest_records(host, conn);
let theirs;
let mut theirs = States::default();
let entities = if elsewhere {
if let Err(e) = self.enter_level(Some(host), level) {
log::error!("could not open {}: {e}", level.id());
return;
}
// A dedicated server has no host player.
theirs = self.lan_entities(None, &mut host.hub);
&theirs[..]
self.lan_entities(None, &mut host.hub, &mut theirs);
theirs.as_slice()
} else {
entities
};
@@ -1207,6 +1188,8 @@ impl Game<'_> {
.each_ref()
.map(|s| s.as_ref().map(|s| s.item.clone()));
m.extra.crouching = g.sneaking;
// Lying in its bed (LivingEntity.getBedOrientation).
m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b));
// LivingEntity.updateSwingTime: the arm swing lan_swings started.
m.anim.attack_anim_o = m.anim.attack_anim;
horizon_client::mobs::ai::tick_swing(m);
@@ -1218,6 +1201,20 @@ impl Game<'_> {
}
}
/// The bed at `head` as a sleeping model lies in it (`ints[1]`,
/// `villager::sleep_pose`): its `facing`.
pub(super) fn bed_facing(&self, head: [i32; 3]) -> i32 {
let state = self.world.block(head[0], head[1], head[2]);
let facing = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing"))
.map(String::as_str);
horizon_client::mobs::villager::bed_facing_code(facing)
}
/// The guests' models for the entity pass.
pub(super) fn guest_model_geometry(
&self,
+216 -25
View File
@@ -53,6 +53,10 @@ pub(super) struct GuestPlay {
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
pub(super) crafting: super::lan_crafting::GuestCrafting,
/// The workstation menu the guest has open (game/lan_stations.rs).
pub(super) station: Option<super::lan_stations::GuestStation>,
/// The lectern the guest reads (game/lan_stations.rs).
pub(super) lectern: Option<super::lan_stations::GuestLectern>,
/// What the guest's body was given for its effects and enchantments.
potions: super::potions::BodyPotions,
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
@@ -64,6 +68,12 @@ pub(super) struct GuestPlay {
xp_delay: u32,
/// What last killed the guest outright (`/kill`): the death message's key.
death_cause: Option<String>,
/// The equipment modifiers on the guest's attributes (`apply_equipment`)
/// and the armour and main hand they were put on for: the hub's player
/// is a `ServerPlayer` too, whose worn armour counts
/// (`LivingEntity.collectEquipmentChanges`).
modifiers: Vec<(String, String)>,
equipped: Option<Vec<Option<ItemStack>>>,
}
/// A guest's command waiting for the hub (`LanHost::commands`).
@@ -130,6 +140,8 @@ pub(super) struct GuestSwap {
swings: u32,
/// How many projectiles there were: those added since are the guest's.
projectiles: usize,
/// The host's equipment modifiers.
modifiers: Vec<(String, String)>,
}
impl GuestPlay {
@@ -193,15 +205,25 @@ impl Game<'_> {
return None;
}
let i = host.hub.guests.iter().position(|g| g.conn == conn)?;
if host.hub.guests[i].motion.is_none() {
let fresh = host.hub.guests[i].motion.is_none();
if fresh {
let p = Vec3::new(
host.hub.guests[i].position[0],
host.hub.guests[i].position[1],
host.hub.guests[i].position[2],
);
host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new);
let kept = host.hub.guests[i].logs_kept.take();
if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) {
m.hurt_log = hurts;
m.attack_log = attacks;
}
}
let mut play = host.play.remove(&conn).unwrap_or_default();
if fresh {
// A new body (joined, respawned, changed level): nothing on it yet.
play.equipped = None;
}
let g = &mut host.hub.guests[i];
// The guest's body.
let Some(mut motion) = g.motion.take() else {
@@ -305,6 +327,17 @@ impl Game<'_> {
let packets = std::mem::take(&mut self.guest_packets);
let swings = self.swings_started;
let projectiles = self.creatures.projectiles.len();
let modifiers = std::mem::replace(
&mut self.applied_modifiers,
std::mem::take(&mut play.modifiers),
);
// Its worn armour on its attributes, when it changed.
let mut equipped: Vec<Option<ItemStack>> = self.armor.to_vec();
equipped.push(self.inventory.get(self.selected).cloned().flatten());
if play.equipped.as_ref() != Some(&equipped) {
self.apply_equipment();
play.equipped = Some(equipped);
}
Some(GuestSwap {
conn,
i,
@@ -350,6 +383,7 @@ impl Game<'_> {
packets,
swings,
projectiles,
modifiers,
})
}
@@ -401,7 +435,9 @@ impl Game<'_> {
packets,
swings,
projectiles,
modifiers,
} = swap;
play.modifiers = std::mem::replace(&mut self.applied_modifiers, modifiers);
// What the guest shot is theirs (Projectile.setOwner).
for p in self.creatures.projectiles.iter_mut().skip(projectiles) {
if p.owner == Some(horizon_client::mobs::Who::Player) && p.guest.is_none() {
@@ -444,7 +480,13 @@ impl Game<'_> {
self.container = container;
self.screen = screen;
self.sign_edit = host_sign;
self.book = host_book;
// A lectern the guest's use opened (LecternBlock.openScreen).
let guest_lectern = match std::mem::replace(&mut self.book, host_book) {
Some(super::books::BookScreen::View {
lectern: Some(key), ..
}) => Some(key),
_ => None,
};
self.command_block_screen = host_command_block;
self.mount_menu = host_mount_menu;
self.keys = host_keys;
@@ -500,12 +542,14 @@ impl Game<'_> {
g.health = m.health.health();
g.food = m.health.food.food;
g.saturation = m.health.food.saturation;
// A teleport (commands) moves the guest.
// A teleport (commands, a pearl) moves the guest; a pearl's is
// sent even to where they stand (ServerPlayer.teleport).
let at = [m.position.x, m.position.y, m.position.z];
m.sprinting = false;
let teleported = std::mem::take(&mut m.teleported);
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
g.motion = Some(Box::new(m));
if moved > 0.0001 || turned {
if moved > 0.0001 || turned || teleported {
host.hub.teleport(i, Some(at));
}
}
@@ -539,6 +583,9 @@ impl Game<'_> {
if let Some(station) = opened_station {
self.lan_station_opened(host, conn, station);
}
if let Some(key) = guest_lectern {
self.lan_open_lectern(host, conn, key);
}
if opened_table {
self.lan_open_crafting(host, conn);
}
@@ -605,6 +652,13 @@ impl Game<'_> {
_ => ("minecraft:furnace", "container.furnace"),
};
(menu, title, Slots::Block(pos))
} else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) {
// CrafterBlock.useWithoutItem: CrafterMenu over the block entity.
(
"minecraft:crafter_3x3",
"container.crafter",
Slots::Block(pos),
)
} else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) {
// BrewingStandBlock.useWithoutItem: BrewingStandMenu.
(
@@ -647,6 +701,7 @@ impl Game<'_> {
};
// ServerPlayer.openMenu closes the menu that was open.
self.guest_container_closed(host, conn);
self.lan_station_closed(host, conn, None);
host.hub.open_container(
conn,
menu,
@@ -717,6 +772,7 @@ impl Game<'_> {
conn,
&C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }),
);
self.destroy_block_progress(host.hub.guests[gi].entity_id, a.pos, -1);
host.hub.broadcast_near(
[
f64::from(a.pos[0]),
@@ -799,6 +855,8 @@ impl Game<'_> {
],
};
let hand = if p.hand == 1 { Hand::Off } else { Hand::Main };
let logged = self.world.block_log.as_ref().map_or(0, Vec::len);
let heard = self.audio.capture.as_ref().map_or(0, Vec::len);
let swung = self.as_guest(host, conn, |g| {
g.forced_hit = Some(hit);
g.guest_use = Some(GuestUse::OnBlock(hand));
@@ -809,6 +867,7 @@ impl Game<'_> {
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
self.guest_use_sounds(host, conn, logged, heard);
// The client predicted a result: correct it with what really is.
for pos in [
p.pos,
@@ -877,6 +936,16 @@ impl Game<'_> {
S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {}
S::ContainerButtonClick(p) => {
self.lan_station_button(host, conn, p.container, p.button);
}
S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name),
S::ContainerSlotStateChanged(p) => {
self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled);
}
S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary),
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
@@ -884,7 +953,10 @@ impl Game<'_> {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => {
S::ContainerClose(p)
if self.lan_crafting_closed(host, conn, Some(p.container))
|| self.lan_station_closed(host, conn, Some(p.container)) =>
{
let g = &mut host.hub.guests[gi];
if let Some(c) = g.carried.take() {
self.drop_guest_items(host, gi, vec![c]);
@@ -1082,12 +1154,23 @@ impl Game<'_> {
gi: usize,
id: i32,
) -> Option<([f64; 3], [f64; 3])> {
let m = self.mobs.iter().find(|m| m.id as i32 == id)?;
let centre = [
m.position.x,
m.position.y + m.kind.height * 0.5,
m.position.z,
];
let centre = match self.mobs.iter().find(|m| m.id as i32 == id) {
Some(m) => [
m.position.x,
m.position.y + m.kind.height * 0.5,
m.position.z,
],
// A dragon part or an end crystal (game/dragon.rs).
None => {
let b = self.tracked_special_box(id)?;
let (lo, hi) = (b.min_position(), b.max_position());
[
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
]
}
};
let g = &mut host.hub.guests[gi];
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let d = [centre[0] - eye[0], centre[1] - eye[1], centre[2] - eye[2]];
@@ -1110,6 +1193,22 @@ impl Game<'_> {
}
return;
}
// A ghast's fireball or a wind charge: turned along the guest's own
// view (ServerGamePacketListenerImpl.handleInteract, then
// Player.attack's AIM_DEFLECT).
if let Some(i) = self
.creatures
.projectiles
.iter()
.position(|p| p.id != 0 && p.id as i32 == id && super::deflect::redirectable(p))
{
self.as_guest(host, conn, |g| {
if g.within_interaction_range(i) {
g.deflect(i);
}
});
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;
@@ -1336,7 +1435,10 @@ impl Game<'_> {
g.food = 20;
g.saturation = 5.0;
g.sent_health = None;
g.motion = None;
if let Some(m) = g.motion.take() {
let m = *m;
g.logs_kept = Some((m.hurt_log, m.attack_log));
}
let mut xp = Experience {
level: g.xp_level,
progress: g.xp_progress,
@@ -1372,6 +1474,7 @@ impl Game<'_> {
/// Per tick, for every guest: dig, use items, pick up drops, die.
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
self.lan_merchant_tick(host);
self.lan_stations_tick(host);
self.announce_guest_advancements(host);
let conns: Vec<u32> = host
.hub
@@ -1684,7 +1787,12 @@ impl Game<'_> {
play.mining = None;
let start = play.dig_start;
let state = self.world.block(pos[0], pos[1], pos[2]);
if !dug || self.res.facts().is_air(state) {
if !dug {
return;
}
if self.res.facts().is_air(state) {
// Already broken (the guest's own tick dug it out): only the crack goes.
self.guest_crack_gone(host, conn, pos);
return;
}
let progress = self
@@ -1733,18 +1841,7 @@ impl Game<'_> {
self.as_guest(host, conn, |g| {
let _ = g.break_block(pos);
});
if let Some(g) = host.hub.guest(conn) {
host.hub.broadcast_near(
[f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
64.0,
&C::BlockDestruction(play::BlockDestruction {
id: g.entity_id,
pos,
progress: 255,
}),
Some(conn),
);
}
self.guest_crack_gone(host, conn, pos);
}
/// The crack animation other players see.
@@ -1756,6 +1853,18 @@ impl Game<'_> {
let Some((pos, _)) = play.digging else {
return;
};
// ServerPlayerGameMode.tick: a block gone while it is dug (the guest's own tick broke
// it, or something else did) clears the crack.
if play.last_progress >= 0
&& self
.res
.facts()
.is_air(self.world.block(pos[0], pos[1], pos[2]))
{
play.last_progress = -1;
self.guest_crack_gone(host, conn, pos);
return;
}
let progress = play
.mining
.as_ref()
@@ -1763,6 +1872,8 @@ impl Game<'_> {
let swinging = play.swing.swinging();
if progress != play.last_progress && progress >= 0 {
play.last_progress = progress;
// The host player sees it too (on the server thread its window is a guest).
self.destroy_block_progress(host.hub.guests[gi].entity_id, pos, progress);
host.hub.broadcast_near(
[f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
64.0,
@@ -1777,6 +1888,25 @@ impl Game<'_> {
let _ = swinging;
}
/// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the
/// host and the other guests.
fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) {
let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else {
return;
};
self.destroy_block_progress(id, pos, -1);
host.hub.broadcast_near(
[f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
64.0,
&C::BlockDestruction(play::BlockDestruction {
id,
pos,
progress: 255,
}),
Some(conn),
);
}
/// Dropped items touching a guest go into their inventory.
fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) {
let (conn, mode, position, id) = {
@@ -1915,6 +2045,33 @@ impl Game<'_> {
}
}
/// `level.playSound(player, ...)` of a guest's use it predicted (`remote::hand_operated`
/// blocks only, as the guest decides): the others hear it now, the guest already did.
fn guest_use_sounds(&mut self, host: &mut LanHost, conn: u32, logged: usize, heard: usize) {
let changed: Vec<(i32, i32, i32)> = self
.world
.block_log
.as_ref()
.map_or(&[][..], |log| log.get(logged..).unwrap_or(&[]))
.to_vec();
let facts = self.res.facts();
if changed.is_empty()
|| !changed.iter().all(|&(x, y, z)| {
super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name)
})
{
return;
}
let Some(capture) = self.audio.capture.as_mut() else {
return;
};
let sounds: Vec<_> = capture.drain(heard.min(capture.len())..).collect();
for (name, at, volume, pitch) in sounds {
let source = horizon_client::settings::sound_source(&name) as i32;
host.hub.sound(&name, at, volume, pitch, source, Some(conn));
}
}
/// Positional sounds and level events of the tick, for the guests.
pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) {
let sounds = self.audio.capture.take().unwrap_or_default();
@@ -1981,6 +2138,7 @@ impl Game<'_> {
}
play.swing.tick();
}
self.lan_host_crack(host);
if self.swings_started != host.host_swings {
host.host_swings = self.swings_started;
if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) {
@@ -1992,6 +2150,39 @@ impl Game<'_> {
}
}
impl Game<'_> {
/// The host player's crack, for the guests (`ServerLevel.destroyBlockProgress` from the
/// host's mining): each new stage, and -1 once it stops or breaks the block.
fn lan_host_crack(&mut self, host: &mut LanHost) {
let now = self
.mining
.as_ref()
.and_then(|m| (m.progress > 0.0).then(|| (m.pos, ((m.progress * 10.0) as i32).min(9))));
if now == host.host_crack {
return;
}
let packet = |pos: [i32; 3], progress: u8| {
C::BlockDestruction(play::BlockDestruction {
id: host.host_entity,
pos,
progress,
})
};
let near = |pos: [i32; 3]| [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])];
if let Some((pos, _)) = host.host_crack
&& now.is_none_or(|(p, _)| p != pos)
{
host.hub
.broadcast_near(near(pos), 64.0, &packet(pos, 255), None);
}
if let Some((pos, stage)) = now {
host.hub
.broadcast_near(near(pos), 64.0, &packet(pos, stage as u8), None);
}
host.host_crack = now;
}
}
/// ClientboundSwingAnimationPacket: the hand and the animation (its type and
/// base duration; each client applies the swinger's haste and fatigue).
fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C {
@@ -83,17 +83,16 @@ impl Game<'_> {
/// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed
/// modifier, its effects' modifiers, its equipment's, and what
/// `/attribute` changed.
pub(super) fn mob_attributes(&self, m: &Mob) -> Vec<AttributeSnapshot> {
pub(super) fn mob_attributes(&self, m: &Mob, out: &mut Vec<AttributeSnapshot>) {
let kind = m.kind.id.as_str();
let mut out = Vec::new();
if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") {
instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed));
instance(out, a, finalize::base_value(m, Attr::MovementSpeed));
}
if let Some(s) = m.extra.attributes.as_deref() {
for (attr, v) in &s.bases {
if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name()))
{
instance(&mut out, a, *v).base = *v;
instance(out, a, *v).base = *v;
}
}
for x in &s.modifiers {
@@ -101,7 +100,7 @@ impl Game<'_> {
self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name()))
{
add_modifier(
&mut out,
out,
a,
finalize::base_value(m, x.attr),
AttributeModifier {
@@ -122,7 +121,7 @@ impl Game<'_> {
finalize::transient(m, Attr::MovementSpeed),
) {
add_modifier(
&mut out,
out,
a,
finalize::base_value(m, Attr::MovementSpeed),
AttributeModifier {
@@ -150,7 +149,7 @@ impl Game<'_> {
};
let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute));
add_modifier(
&mut out,
out,
a,
start,
AttributeModifier {
@@ -172,10 +171,9 @@ impl Game<'_> {
("chest", e.chest.as_ref()),
("head", e.head.as_ref()),
],
&mut out,
out,
);
self.generic_attributes_of(Target::Mob(m.id), &mut out);
out
self.generic_attributes_of(Target::Mob(m.id), out);
}
/// An armor stand's synced instances: movement speed (its first
+99 -11
View File
@@ -55,6 +55,7 @@ fn load_player(menu: &mut Menu, g: &Guest) {
menu.set_player_item(OFFHAND, g.offhand.clone());
menu.selected = g.selected;
menu.creative = g.creative();
menu.levels = g.xp_level;
menu.carried = g.carried.clone();
}
@@ -83,27 +84,47 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec<ItemStack>) {
}
impl Game<'_> {
fn menu_env(&self) -> Env<'_> {
pub(super) fn menu_env(&self) -> Env<'_> {
Env {
items: self.res.items(),
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: None,
maps: None,
}
}
/// Runs `op` on the guest's menu with their inventory copied in and back.
fn guest_menu_op<R>(
pub(super) fn guest_menu_op<R>(
&mut self,
host: &mut LanHost,
gi: usize,
menu: &mut Menu,
op: impl FnOnce(&mut Menu, &Env) -> R,
) -> R {
let env = self.menu_env();
// The cartography table reads and makes the host level's maps.
let maps = (menu.kind() == Kind::Cartography).then(|| {
let g = &host.hub.guests[gi];
let held: Vec<ItemStack> = (0..menu.slot_count())
.filter_map(|s| menu.slot(s).cloned())
.chain(g.inventory.iter().flatten().cloned())
.chain(g.carried.clone())
.collect();
self.level_maps(&held)
});
let env = Env {
maps: maps.as_ref().map(|m| m as &dyn horizon_client::menu::Maps),
..self.menu_env()
};
load_player(menu, &host.hub.guests[gi]);
let result = op(menu, &env);
if let Some(maps) = maps {
self.register_made_maps(maps);
}
let dropped = std::mem::take(&mut menu.dropped);
let equipped = std::mem::take(&mut menu.equipped);
menu.drops.clear();
@@ -201,8 +222,14 @@ impl Game<'_> {
(Kind::Furnace(recipe), f.items.to_vec())
}
Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()),
Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()),
_ => return false,
};
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
let crafter_data = match self.world.block_entities.get(&pos) {
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
_ => None,
};
if host.hub.guests[gi].spectator() {
return true;
}
@@ -219,6 +246,13 @@ impl Game<'_> {
for (k, s) in items.iter().enumerate() {
menu.set_slot(env, k, s.clone());
}
// After the slots: setting a disabled slot (CrafterBlockEntity.setItem) enables it.
if let Some((disabled, triggered)) = crafter_data {
for (k, d) in disabled.iter().enumerate() {
menu.data[k] = i32::from(*d);
}
menu.data[9] = i32::from(triggered);
}
let before: Vec<_> = (0..menu.slot_count())
.map(|s| menu.slot(s).cloned())
.collect();
@@ -241,6 +275,13 @@ impl Game<'_> {
b.items[k] = menu.slot(k).cloned();
}
}
// CrafterBlockEntity.setItem: filling a disabled slot enables it.
Some(BlockEntity::Crafter(c)) => {
for k in 0..9 {
c.items[k] = menu.slot(k).cloned();
c.disabled[k] = menu.data[k] == 1;
}
}
_ => {}
}
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
@@ -248,6 +289,39 @@ impl Game<'_> {
true
}
/// `ServerGamePacketListenerImpl.handleContainerSlotStateChanged`: a
/// guest's crafter slot toggle (`CrafterBlockEntity.setSlotState`) in
/// their open crafter window.
pub(super) fn lan_crafter_slot_state(
&mut self,
host: &mut LanHost,
conn: u32,
window: i32,
slot: i32,
enabled: bool,
) {
let Some(pos) = host
.hub
.guest(conn)
.filter(|g| !g.spectator())
.and_then(|g| g.menu.as_ref())
.filter(|m| window != 0 && m.window == window)
.and_then(|m| match m.slots {
Slots::Block(pos) => Some(pos),
_ => None,
})
else {
return;
};
if let (Some(BlockEntity::Crafter(c)), Ok(slot)) = (
self.world.block_entities.get_mut(&pos),
usize::try_from(slot),
) {
c.set_slot_state(slot, enabled);
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
}
}
/// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe
/// book places a known recipe in their inventory grid or crafting table
/// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items
@@ -331,6 +405,7 @@ impl Game<'_> {
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
self.lan_crafting_closed(host, conn, None);
self.lan_station_closed(host, conn, None);
// The container it replaces loses its opener.
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable("container.crafting", &[]);
@@ -430,22 +505,35 @@ impl Game<'_> {
None => return false,
}
};
if grid.is_empty() {
return true;
if !grid.is_empty() {
self.lan_place_back(host, gi, grid);
}
let mut menu = Menu::new(Kind::Inventory);
self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid));
true
}
/// A guest left: what their crafting grids held goes back into their
/// `Inventory.placeItemBackInInventory` of `stacks` for guest `gi`, what
/// doesn't fit dropped (`clearContainer`).
pub(super) fn lan_place_back(&mut self, host: &mut LanHost, gi: usize, stacks: Vec<ItemStack>) {
let mut menu = Menu::new(Kind::Inventory);
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
place_back(menu, env, stacks)
});
}
/// A guest left: what their crafting grids and workstation held goes back into their
/// inventory before it is saved (dropped where they stood if full).
pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) {
let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table);
let play = host.play.remove(&g.conn);
let mut grid: Vec<ItemStack> = g.craft_grid.iter_mut().filter_map(Option::take).collect();
g.craft_result = None;
if let Some((_, _, menu)) = table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
if let Some(play) = play {
if let Some((_, _, menu)) = play.crafting.table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
}
// A workstation's inputs too.
if let Some(station) = &play.station {
grid.extend(super::lan_stations::station_inputs(station));
}
}
if grid.is_empty() {
return;
@@ -5,7 +5,7 @@
//! synched data that differs from the defaults), and who rides what.
use super::Game;
use horizon_client::lan::{
entity::{EntityState, Riding},
entity::{EntityState, Riding, States},
hub::Hub,
};
use horizon_protocol::entity_data::{Value, serializer};
@@ -107,7 +107,7 @@ impl Game<'_> {
&self,
host_entity: Option<i32>,
hub: &mut Hub,
out: &mut Vec<EntityState>,
out: &mut States,
) {
for b in &self.boats {
let p = b.position;
@@ -268,12 +268,7 @@ impl Game<'_> {
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
/// end crystals, as guests track them.
fn lan_projectile_states(
&self,
host_entity: Option<i32>,
hub: &mut Hub,
out: &mut Vec<EntityState>,
) {
fn lan_projectile_states(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
let owner = |who: Option<horizon_client::mobs::Who>| match who {
Some(horizon_client::mobs::Who::Mob(id)) => id as i32,
Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0),
@@ -406,6 +401,7 @@ impl Game<'_> {
}
out.push(e);
}
out.extend(self.lan_dragon_state());
}
}
+101 -1
View File
@@ -3,9 +3,26 @@
//! 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`).
//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). A player's arrow on
//! another player lands the same way.
use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector};
use horizon_client::{
Result,
mobs::Who,
projectiles::{Hit, Projectile, ProjectileKind},
};
/// The player projectiles that meet other players: arrows (their hurt), and
/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0
/// damage). Pearls, potions and wind charges fly past players as before.
pub(super) fn meets_players(kind: &ProjectileKind) -> bool {
matches!(
kind,
ProjectileKind::Arrow { .. } | ProjectileKind::Snowball | ProjectileKind::Egg
)
}
/// Who a player's attack lands on.
#[derive(Clone, Copy)]
pub(super) enum Victim {
@@ -105,6 +122,89 @@ impl Game<'_> {
})
}
/// The guests by connection, with their entity ids.
pub(super) fn lan_guest_entities(&self) -> Vec<(u32, u32)> {
self.lan.as_ref().map_or_else(Vec::new, |host| {
host.hub
.guests
.iter()
.map(|g| (g.conn, g.entity_id as u32))
.collect()
})
}
/// The player a player's projectile hit, when it hit one: the host for a
/// guest's shot, or a guest.
pub(super) fn projectile_pvp_victim(&self, p: &Projectile, hit: Hit) -> Option<Victim> {
if p.owner != Some(Who::Player) || !meets_players(&p.kind) {
return None;
}
let Hit::Entity { who, .. } = hit else {
return None;
};
match who {
Who::Player => p.guest.map(|_| Victim::Host),
Who::Mob(id) => self
.lan
.as_ref()?
.hub
.guests
.iter()
.find(|g| g.entity_id as u32 == id)
.map(|g| Victim::Guest(g.conn)),
}
}
/// A player's projectile on a player: the hit runs as the victim, whose
/// hurt refuses it when the `pvp` game rule or their teams forbid it
/// (`ServerPlayer.canHarmPlayer`; `AbstractArrow.onHitEntity` then turns
/// the arrow back).
pub(super) fn projectile_hits_player(
&mut self,
p: &Projectile,
hit: Hit,
victim: Victim,
) -> Result<()> {
let Hit::Entity { at, .. } = hit else {
return Ok(());
};
let Some(mut host) = self.lan.take() else {
return self.projectile_hit(p, hit);
};
let team_of = |game: &Self, name: &str| game.score.board.players_team(name).cloned();
let attacker = match p.guest {
Some(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)),
None => self.player_team().cloned(),
};
let target = match victim {
Victim::Host => self.player_team().cloned(),
Victim::Guest(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)),
};
let refused = !(self.ui.rules.bool("pvp")
&& horizon_client::scoreboard::teams_allow_damage(target.as_ref(), attacker.as_ref()));
let on_player = Hit::Entity {
who: Who::Player,
at,
};
let result = match victim {
Victim::Host => {
self.lan = Some(host);
self.combat.refuse_player_hit = refused;
let r = self.projectile_hit(p, on_player);
self.combat.refuse_player_hit = false;
return r;
}
Victim::Guest(conn) => self.guest_hit_by(&mut host, conn, |g| {
g.combat.refuse_player_hit = refused;
let r = g.projectile_hit(p, on_player);
g.combat.refuse_player_hit = false;
r
}),
};
self.lan = Some(host);
result.unwrap_or(Ok(()))
}
/// The hit landing on the victim with its extra knockback, then the
/// attacker's attack sound. Whether the victim was hurt.
pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) -> bool {
@@ -0,0 +1,672 @@
//! Workstation menus for LAN guests: the screen a guest's use opens runs on
//! the host's menu engine (`horizon_client::menu`), the one single player
//! uses, with vanilla's packets: OpenScreen with the station's `MenuType`,
//! container clicks, `ServerboundContainerButtonClickPacket`, the content and
//! data slot sync after each (`broadcastChanges`), and the inputs back into
//! the inventory when the menu closes (`AbstractContainerMenu.clearContainer`).
use super::{
Game,
lan::LanHost,
lan_crafting::input,
stations::{Kind as StationKind, Station},
};
use horizon_client::{
containers::BlockEntity,
items::ItemStack,
menu::{Kind, Menu},
};
use horizon_core::random::RandomSource;
use horizon_protocol::packets::play::{self, Clientbound as C};
/// A guest's open workstation menu.
pub(super) struct GuestStation {
window: i32,
state: i32,
kind: StationKind,
pos: [i32; 3],
menu: Box<Menu>,
/// The data slots the client was last sent.
sent_data: Vec<i32>,
/// The game time of the menu's last sound (`lastSoundTime`).
last_sound: u64,
}
/// A guest's open lectern: `LecternMenu` over the block entity, made on the
/// menu engine for each click (`Game::lectern_menu`).
pub(super) struct GuestLectern {
window: i32,
state: i32,
key: (i32, i32, i32),
/// The book and page the client was last sent (`broadcastChanges`).
sent: Option<(Option<ItemStack>, i32)>,
}
/// The `MenuType`, the engine's menu and the input slots
/// (`clearContainer`'s container) of a station a guest can use.
fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range<usize>)> {
Some(match kind {
StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3),
StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1),
StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2),
StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2),
StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3),
StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2),
StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1),
StationKind::Cartography => ("minecraft:cartography_table", Kind::Cartography, 0..2),
_ => return None,
})
}
impl Game<'_> {
/// A workstation a guest's use opened (`ServerPlayer.openMenu`); false
/// when guests can't use that one yet.
pub(super) fn lan_open_station(
&mut self,
host: &mut LanHost,
conn: u32,
station: &Station,
) -> bool {
let Some((menu_type, kind, _)) = menu_of(station.kind) else {
return false;
};
self.lan_station_closed(host, conn, None);
self.lan_crafting_closed(host, conn, None);
// The container it replaces loses its opener.
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable(station.kind.title_key(), &[]);
let Some(window) = host.hub.open_window(conn, menu_type, title) else {
return true;
};
let mut menu = Box::new(Menu::new(kind));
if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn)
&& kind == Kind::Enchanting
{
// Player.enchantmentSeed, made when first needed.
if g.xp_seed == 0 {
g.xp_seed = self.world.random.next_int();
}
menu.data[3] = g.xp_seed;
}
if kind == Kind::Beacon {
menu.data = self.beacon_data(host, station.pos).to_vec();
}
host.play.entry(conn).or_default().station = Some(GuestStation {
window,
state: 0,
kind: station.kind,
pos: station.pos,
menu,
sent_data: Vec::new(),
last_sound: 0,
});
self.lan_send_station(host, conn);
true
}
/// Runs `op` on the guest's open station (window `window`, any when
/// None) with their inventory in it, then sends what changed. False when
/// no such window is open.
fn lan_station_op(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
op: impl FnOnce(&mut Menu, &horizon_client::menu::Env),
) -> bool {
let Some(mut gs) = host
.play
.get_mut(&conn)
.and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w)))
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
{
self.guest_menu_op(host, gi, &mut gs.menu, op);
self.lan_station_sounds(&mut gs);
if let Some(amount) = gs.menu.ground.take() {
self.grindstone_taken(gs.pos, amount);
}
self.lan_station_combined(host, conn, &mut gs);
if let Some(button) = gs.menu.enchant_button.take() {
self.lan_enchant(host, gi, &mut gs, button);
}
if std::mem::take(&mut gs.menu.enchant_changed) {
self.lan_enchant_offers(host, gi, &mut gs);
}
}
host.play.entry(conn).or_default().station = Some(gs);
self.lan_send_station(host, conn);
true
}
/// `LecternBlock.openScreen` for a guest: `minecraft:lectern` over the
/// block entity, with its book and page.
pub(super) fn lan_open_lectern(&mut self, host: &mut LanHost, conn: u32, key: (i32, i32, i32)) {
self.lan_station_closed(host, conn, None);
self.lan_crafting_closed(host, conn, None);
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable("container.lectern", &[]);
let Some(window) = host.hub.open_window(conn, "minecraft:lectern", title) else {
return;
};
host.play.entry(conn).or_default().lectern = Some(GuestLectern {
window,
state: 0,
key,
sent: None,
});
self.lan_send_lectern(host, conn, true);
}
/// The lectern's book and page for the client: everything (`all`), or
/// what changed since it was last sent.
fn lan_send_lectern(&mut self, host: &mut LanHost, conn: u32, all: bool) {
let Some(gl) = host.play.get_mut(&conn).and_then(|p| p.lectern.as_mut()) else {
return;
};
let (book, page) = match self.world.block_entities.get(&gl.key) {
Some(BlockEntity::Lectern(l)) => (l.book.clone(), l.page),
_ => (None, 0),
};
let now = Some((book.clone(), page));
if !all && gl.sent == now {
return;
}
let page_changed = gl.sent.as_ref().is_none_or(|(_, p)| *p != page);
gl.sent = now;
gl.state = (gl.state + 1) & 0x7FFF;
let (window, state) = (gl.window, gl.state);
let carried = host
.hub
.guests
.iter()
.find(|g| g.conn == conn)
.and_then(|g| g.carried.clone());
let content = C::ContainerSetContent(play::ContainerSetContent {
container: window,
state,
items: vec![host.hub.stack(&book)],
carried: host.hub.stack(&carried),
});
host.hub.send_to(conn, &content);
if all || page_changed {
host.hub.send_to(
conn,
&C::ContainerSetData(play::ContainerSetData {
container: window,
id: 0,
value: page as i16,
}),
);
}
}
/// Runs `op` on the guest's lectern menu (window `window`) with their
/// inventory, the block entity takes the book and page back, and the
/// client gets what changed. False when no such window is open.
fn lan_lectern_op(
&mut self,
host: &mut LanHost,
conn: u32,
window: i32,
op: impl FnOnce(&mut Menu, &horizon_client::menu::Env),
) -> bool {
let Some(key) = host
.play
.get(&conn)
.and_then(|p| p.lectern.as_ref())
.filter(|l| l.window == window)
.map(|l| l.key)
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
&& let Some(mut menu) = self.lectern_menu(key)
{
// Player.mayBuild: survival and creative.
let may_build = matches!(host.hub.guests[gi].game_mode, 0 | 1);
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
menu.may_build = may_build;
op(menu, env);
});
self.lectern_menu_done(key, &menu);
}
self.lan_send_lectern(host, conn, true);
true
}
/// A click on the guest's lectern window; false for other windows.
pub(super) fn lan_lectern_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
self.lan_lectern_op(host, conn, p.container, |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
})
}
/// The rest of a taken anvil or smithing result's `onTake`: the guest
/// pays the levels, the anvil wears (level event 1030 or 1029), the
/// smithing table sounds (1044).
fn lan_station_combined(&mut self, host: &mut LanHost, conn: u32, gs: &mut GuestStation) {
let change = std::mem::take(&mut gs.menu.level_change);
if change != 0 {
self.as_guest(host, conn, |g| g.give_levels(change));
}
if !std::mem::take(&mut gs.menu.combined) {
return;
}
if gs.kind == StationKind::Smithing {
self.level_event_at(1044, gs.pos, 0);
} else {
let creative = gs.menu.creative;
// A broken anvil closes the menu on the next stillValid check.
self.anvil_used(gs.pos, creative);
}
}
/// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for
/// the guest's seed and the bookshelves around the table.
fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) {
let seed = host.hub.guests[gi].xp_seed;
let bookcases = self.count_bookshelves(gs.pos);
let offers = horizon_client::stations::enchant_offers(
&self.res.stations().enchantments,
self.res.items(),
seed,
bookcases,
gs.menu.slot(0),
);
for i in 0..3 {
gs.menu.data[i] = offers.costs[i];
let clue = offers.clues[i].as_ref();
gs.menu.data[4 + i] = clue
.and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e))
.unwrap_or(-1);
gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32);
}
gs.menu.data[3] = seed;
}
/// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets
/// the offer's enchantments, the guest pays its levels and lapis and
/// gets a new seed, the table sounds, and the offers are made again.
fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) {
let Some(item) = gs.menu.slot(0).cloned() else {
return;
};
let g = &host.hub.guests[gi];
let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn);
let Some(enchanted) = horizon_client::stations::apply_enchantment(
&self.res.stations().enchantments,
self.res.items(),
seed,
button,
gs.menu.data[button],
&item,
) else {
return;
};
let need = button as i32 + 1;
// Player.onEnchantmentPerformed, and EnchantmentMenu's awardStat(ENCHANT_ITEM).
self.as_guest(host, conn, |game| {
game.give_levels(-need);
game.stats.custom("enchant_item", 1);
});
host.hub.guests[gi].xp_seed = self.world.random.next_int();
let env = self.menu_env();
let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| {
l.count = l.count.saturating_sub(need as u32);
l
});
gs.menu.set_slot(&env, 0, Some(enchanted));
if !creative {
gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0));
}
gs.menu.enchant_changed = false;
self.lan_enchant_offers(host, gi, gs);
let pitch = self.world.random.next_float() * 0.1 + 0.9;
let at = gs.pos.map(|v| f64::from(v) + 0.5);
self.audio.play(
"minecraft:block.enchantment_table.use",
Some(at),
1.0,
pitch,
);
}
/// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil
/// takes the name (`AnvilMenu.setItemName`).
pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) {
let anvil = host
.play
.get(&conn)
.and_then(|p| p.station.as_ref())
.is_some_and(|s| s.kind == StationKind::Anvil);
if anvil {
self.lan_station_op(host, conn, None, |menu, env| {
menu.rename(env, name);
});
}
}
/// The sounds the menu played, at the station (heard by everyone around,
/// as `level.playSound(null, pos, ...)`), once per tick.
fn lan_station_sounds(&mut self, gs: &mut GuestStation) {
let sounds = std::mem::take(&mut gs.menu.sounds);
if sounds.is_empty() || gs.last_sound == self.ticks {
return;
}
gs.last_sound = self.ticks;
let at = gs.pos.map(|v| f64::from(v) + 0.5);
for sound in sounds {
self.audio.play(sound, Some(at), 1.0, 1.0);
}
}
/// A click on the guest's station window; false for other windows.
pub(super) fn lan_station_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
self.lan_station_op(host, conn, Some(p.container), |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
})
}
/// `ServerGamePacketListenerImpl.handleContainerButtonClick`:
/// `clickMenuButton`, then `broadcastChanges` when the menu took it.
pub(super) fn lan_station_button(
&mut self,
host: &mut LanHost,
conn: u32,
window: i32,
id: i32,
) {
// LecternMenu's page buttons and Take Book.
if self.lan_lectern_op(host, conn, window, |menu, env| {
menu.button(env, id);
}) {
return;
}
self.lan_station_op(host, conn, Some(window), |menu, env| {
menu.button(env, id);
});
}
/// The whole station menu and its changed data slots for the client
/// (`sendAllDataToRemote` / `broadcastChanges`).
fn lan_send_station(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) else {
return;
};
gs.state = (gs.state + 1) & 0x7FFF;
let own = gs.menu.slot_count() - 36;
let mut items: Vec<Option<ItemStack>> =
(0..own).map(|s| gs.menu.slot(s).cloned()).collect();
let g = &host.hub.guests[gi];
items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
let carried = g.carried.clone();
let packet = C::ContainerSetContent(play::ContainerSetContent {
container: gs.window,
state: gs.state,
items: items.iter().map(|s| host.hub.stack(s)).collect(),
carried: host.hub.stack(&carried),
});
gs.sent_data.resize(gs.menu.data.len(), i32::MIN);
let mut data = Vec::new();
for (k, &v) in gs.menu.data.iter().enumerate() {
if gs.sent_data[k] != v {
gs.sent_data[k] = v;
data.push(C::ContainerSetData(play::ContainerSetData {
container: gs.window,
id: k as i16,
value: v as i16,
}));
}
}
host.hub.send_to(conn, &packet);
for packet in data {
host.hub.send_to(conn, &packet);
}
}
/// `AbstractContainerMenu.removed` of the guest's station (`window`;
/// None closes it whichever it is): the carried stack and the inputs go
/// back to the inventory, what doesn't fit is dropped. False when no such
/// window is open.
pub(super) fn lan_station_closed(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
) -> bool {
// A lectern's menu keeps nothing of its own (the book is the block entity's).
let lectern = host
.play
.get_mut(&conn)
.and_then(|p| p.lectern.take_if(|l| window.is_none_or(|w| l.window == w)));
if lectern.is_some() {
// AbstractContainerMenu.removed: the carried stack goes back.
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& let Some(carried) = host.hub.guests[gi].carried.take()
{
self.lan_place_back(host, gi, vec![carried]);
}
if window.is_some() {
return true;
}
}
let Some(gs) = host
.play
.get_mut(&conn)
.and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w)))
else {
return false;
};
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return true;
};
// AbstractContainerMenu.removed: the carried stack first, then the inputs.
let mut back: Vec<ItemStack> = host.hub.guests[gi].carried.take().into_iter().collect();
let inputs = station_inputs(&gs);
if gs.kind == StationKind::Beacon {
// BeaconMenu.removed drops the payment (player.drop).
if !back.is_empty() {
self.lan_place_back(host, gi, std::mem::take(&mut back));
}
self.drop_guest_items(host, gi, inputs);
} else {
back.extend(inputs);
}
if !back.is_empty() {
self.lan_place_back(host, gi, back);
}
true
}
/// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers
/// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none).
fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] {
let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
else {
return [0; 3];
};
let encode = |e: &Option<String>| {
e.as_deref()
.and_then(|n| host.hub.registry_id("minecraft:mob_effect", n))
.map_or(0, |id| id + 1)
};
[b.levels, encode(&b.primary), encode(&b.secondary)]
}
/// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's
/// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they
/// become the block entity's (`dataAccess.set`: the power_select sound
/// while the beam is up).
pub(super) fn lan_station_beacon(
&mut self,
host: &mut LanHost,
conn: u32,
primary: Option<i32>,
secondary: Option<i32>,
) {
let Some(pos) = host
.play
.get(&conn)
.and_then(|p| p.station.as_ref())
.filter(|s| s.kind == StationKind::Beacon)
.map(|s| s.pos)
else {
return;
};
// An id the registry doesn't have fails the packet's codec.
let mut powers: [Option<(i32, String)>; 2] = [None, None];
for (k, id) in [primary, secondary].into_iter().enumerate() {
if let Some(id) = id {
let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else {
return;
};
powers[k] = Some((id, name.to_owned()));
}
}
let data = self.beacon_data(host, pos);
let mut updated = false;
self.lan_station_op(host, conn, None, |menu, env| {
menu.data.copy_from_slice(&data);
let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str()));
updated = menu.beacon_update(env, power(0), power(1));
});
if !updated {
return;
}
let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n));
let mut select_sound = false;
if let Some(BlockEntity::Beacon(b)) =
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
{
b.primary = primary;
b.secondary = secondary;
select_sound = !b.sections.is_empty();
}
if select_sound {
self.beacon_sound(pos, "minecraft:block.beacon.power_select");
}
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
}
/// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its
/// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`).
pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) {
self.lan_lecterns_tick(host);
let conns: Vec<u32> = host
.play
.iter()
.filter(|(_, p)| p.station.is_some())
.map(|(c, _)| *c)
.collect();
for conn in conns {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let Some(gs) = host.play.get(&conn).and_then(|p| p.station.as_ref()) else {
continue;
};
let [x, y, z] = gs.pos;
let name = &self.res.facts().get(self.world.block(x, y, z)).name;
let block = StationKind::from_block(name) == Some(gs.kind);
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
// The block interaction range (4.5, creative 5) and the buffer.
let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0;
let near = (0..3)
.map(|k| {
let lo = f64::from(gs.pos[k]);
(lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2)
})
.sum::<f64>()
< reach * reach;
if !(block && near) {
let window = gs.window;
self.lan_station_closed(host, conn, Some(window));
host.hub.send_to(
conn,
&C::ContainerClose(play::ContainerClose { container: window }),
);
} else if gs.kind == StationKind::Beacon {
// The beacon's data slots follow its block entity.
let data = self.beacon_data(host, gs.pos);
if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut())
&& gs.menu.data[..] != data[..]
{
gs.menu.data.copy_from_slice(&data);
self.lan_send_station(host, conn);
}
}
}
}
}
impl Game<'_> {
/// The guests' lecterns each tick: `stillValid` (the block entity, its
/// book, the reach) closes them, and `broadcastChanges` sends a book or
/// page another player changed.
fn lan_lecterns_tick(&mut self, host: &mut LanHost) {
let open: Vec<(u32, i32, (i32, i32, i32))> = host
.play
.iter()
.filter_map(|(c, p)| p.lectern.as_ref().map(|l| (*c, l.window, l.key)))
.collect();
for (conn, window, key) in open {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let has_book = matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Lectern(l)) if l.book.is_some()
);
// Container.stillValidBlockEntity: the interaction range and its buffer.
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0;
let pos = [key.0, key.1, key.2];
let near = (0..3)
.map(|k| {
let lo = f64::from(pos[k]);
(lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2)
})
.sum::<f64>()
< reach * reach;
if has_book && near {
self.lan_send_lectern(host, conn, false);
} else {
self.lan_station_closed(host, conn, Some(window));
host.hub.send_to(
conn,
&C::ContainerClose(play::ContainerClose { container: window }),
);
}
}
}
}
/// What `clearContainer` gives back from a station's menu.
pub(super) fn station_inputs(gs: &GuestStation) -> Vec<ItemStack> {
menu_of(gs.kind)
.map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect())
.unwrap_or_default()
}
+10 -3
View File
@@ -55,8 +55,9 @@ impl Game<'_> {
state.session.update_special_prices();
}
let title = self.merchant_display_name(&state);
// The container the trading screen replaces loses its opener.
// The container or workstation the trading screen replaces is closed.
self.guest_container_closed(host, conn);
self.lan_station_closed(host, conn, None);
let Some(window) = host.hub.open_merchant_window(conn, title) else {
self.merchant_closed(&mut state);
return;
@@ -254,7 +255,11 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: Some(&trade_env),
maps: None,
};
let mut menu = Menu::new(Kind::Merchant);
{
@@ -393,8 +398,8 @@ impl Game<'_> {
});
}
}
/// Takes a station a guest's action opened: a trading screen goes to the
/// guest; other stations are not shown to guests yet.
/// Takes a station a guest's action opened: a trading screen or a
/// workstation menu goes to the guest (game/lan_stations.rs).
pub(super) fn lan_station_opened(
&mut self,
host: &mut LanHost,
@@ -406,6 +411,8 @@ impl Game<'_> {
&& let Some(m) = station.merchant.take()
{
self.lan_open_merchant(host, conn, *m);
return;
}
self.lan_open_station(host, conn, &station);
}
}
+72 -36
View File
@@ -1,5 +1,5 @@
//! The locator bar of the players on a served world (lan/waypoints.rs): what
//! each player looks like to the waypoint manager this tick.
//! each player looks like to their level's waypoint manager this tick.
use super::{Game, lan::LanHost};
use horizon_client::{
items::ItemStack,
@@ -27,8 +27,12 @@ impl Game<'_> {
Some((team.name.clone(), color))
}
/// Each level's `ServerWaypointManager` ticked with the players in that
/// level: a player who changes level leaves the old one's manager
/// (`ServerLevel.removePlayerImmediately`: untracked for everyone there)
/// and joins the new one's (`addDuringTeleport`).
pub(super) fn lan_update_waypoints(&mut self, host: &mut LanHost, state: Option<&HostState>) {
let mut players = Vec::new();
let mut players: Vec<(&str, waypoints::Player)> = Vec::new();
if let Some(h) = state {
let icon = self
.cmds
@@ -39,22 +43,25 @@ impl Game<'_> {
color: i.color,
})
.unwrap_or_default();
players.push(waypoints::Player {
uuid: h.uuid,
conn: None,
position: h.position,
spectator: self.spectator(),
transmit_range: transmit_range(
h.sneaking,
self.potions.effects.get("invisibility").is_some(),
h.equipment[5].as_ref(),
),
receive_range: PLAYER_RANGE,
first_tick: false,
view_distance: host.hub.config.view_distance,
team: self.waypoint_team(&h.name),
icon,
});
players.push((
self.dim.id(),
waypoints::Player {
uuid: h.uuid,
conn: None,
position: h.position,
spectator: self.spectator(),
transmit_range: transmit_range(
h.sneaking,
self.potions.effects.get("invisibility").is_some(),
h.equipment[5].as_ref(),
),
receive_range: PLAYER_RANGE,
first_tick: false,
view_distance: host.hub.config.view_distance,
team: self.waypoint_team(&h.name),
icon,
},
));
}
let mut respawned = Vec::new();
for g in host.hub.guests.iter().filter(|g| g.placed) {
@@ -66,27 +73,56 @@ impl Game<'_> {
}
// Player.updatePlayerPose: the shift key crouches unless flying.
let crouching = g.sneaking && !g.flying && !g.fall_flying && !g.sleeping;
players.push(waypoints::Player {
uuid: g.uuid,
conn: Some(g.conn),
position: g.position,
spectator: g.spectator(),
transmit_range: transmit_range(
crouching,
g.effects.get("invisibility").is_some(),
g.armor[0].as_ref(),
),
receive_range: PLAYER_RANGE,
first_tick: g.ticks == 0,
view_distance: g.view_distance,
team: self.waypoint_team(&g.name),
icon: Icon::default(),
});
players.push((
&g.dimension,
waypoints::Player {
uuid: g.uuid,
conn: Some(g.conn),
position: g.position,
spectator: g.spectator(),
transmit_range: transmit_range(
crouching,
g.effects.get("invisibility").is_some(),
g.armor[0].as_ref(),
),
receive_range: PLAYER_RANGE,
first_tick: g.ticks == 0,
view_distance: g.view_distance,
team: self.waypoint_team(&g.name),
icon: Icon::default(),
},
));
}
host.waypoint_dead
.retain(|uuid| players.iter().any(|p| p.uuid == *uuid));
.retain(|uuid| players.iter().any(|(_, p)| p.uuid == *uuid));
let locator_bar = self.ui.rules.bool("locator_bar");
for (conn, packet) in host.waypoints.tick(&players, &respawned, locator_bar) {
let mut levels: Vec<String> = host.waypoints.keys().cloned().collect();
for (level, _) in &players {
if !levels.iter().any(|l| l == level) {
levels.push((*level).to_owned());
}
}
levels.sort();
let mut out = Vec::new();
for level in levels {
let here: Vec<waypoints::Player> = players
.iter()
.filter(|(l, _)| *l == level)
.map(|(_, p)| p.clone())
.collect();
let away: Vec<(u128, u32)> = players
.iter()
.filter(|(l, _)| *l != level)
.filter_map(|(_, p)| Some((p.uuid, p.conn?)))
.collect();
let manager = host.waypoints.entry(level.clone()).or_default();
out.extend(manager.tick_level(&here, &away, &respawned, locator_bar));
// Nobody left in the level: nothing to remember there.
if here.is_empty() {
host.waypoints.remove(&level);
}
}
for (conn, packet) in out {
if let Some(g) = host.hub.guest(conn) {
g.send(&packet);
}
+1 -6
View File
@@ -312,15 +312,10 @@ impl Game<'_> {
.map_or_else(String::new, |(end, start)| {
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
});
let list: Vec<String> = spans
.iter()
.filter(|(_, ms)| *ms >= 0.5)
.map(|(n, ms)| format!("{n} {ms:.1}"))
.collect();
log::info!(
"Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}",
self.mobs.len(),
list.join(", ")
horizon_client::spans::describe(&spans)
);
}
result
+4 -2
View File
@@ -68,8 +68,9 @@ impl Game<'_> {
}
l.last_inputs = inputs;
}
/// A sound the loom menu played: the result's once per tick.
pub(super) fn loom_sound(&mut self, sound: &str) {
/// A sound the loom or stonecutter menu played: the result's once per
/// tick (`lastSoundTime`).
pub(super) fn station_sound(&mut self, sound: &str) {
let ticks = self.ticks;
let Some(s) = self.station.as_mut() else {
return;
@@ -98,6 +99,7 @@ impl Game<'_> {
if taken {
self.audio
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
self.remote_station_button(index as i32);
}
taken
}
+164
View File
@@ -327,6 +327,46 @@ impl Containers<'_> {
}
}
/// The block columns any item entity's box reaches, so that a hopper with
/// no item over it skips the scan of every item. Kept for one block-entity
/// pass, in which items do not move: removing one leaves a superset, still
/// right, and adding one (always pushed at the end, under a new id) or
/// removing the last rebuilds the columns.
#[derive(Default)]
pub(super) struct ItemColumns {
/// The item count and last item id when last asked, if built.
seen: Option<(usize, Option<u32>)>,
cells: horizon_client::fast_hash::FxHashSet<(i32, i32)>,
}
impl ItemColumns {
/// Whether an item's box may reach into column (x, z).
fn may_reach(
&mut self,
items: &[horizon_client::entities::ItemEntity],
x: i32,
z: i32,
) -> bool {
let (len, last) = (items.len(), items.last().map(|i| i.id));
let stale = self
.seen
.is_none_or(|(seen_len, seen_last)| len > seen_len || last != seen_last);
self.seen = Some((len, last));
if stale {
self.cells.clear();
for item in items {
let b = item.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
for cx in lo.x.floor() as i32..=hi.x.floor() as i32 {
for cz in lo.z.floor() as i32..=hi.z.floor() as i32 {
self.cells.insert((cx, cz));
}
}
}
}
self.cells.contains(&(x, z))
}
}
fn bone_meal() -> ItemStack {
ItemStack {
item: "minecraft:bone_meal".into(),
@@ -648,6 +688,11 @@ impl Game<'_> {
f64::from(pos.2) + 1.0,
],
);
if let Some(columns) = self.item_columns.as_mut()
&& !columns.may_reach(&self.dropped, pos.0, pos.2)
{
return false;
}
let mut i = 0;
while i < self.dropped.len() {
let b = self.dropped[i].bounds();
@@ -880,3 +925,122 @@ impl Game<'_> {
true
}
}
#[cfg(test)]
mod item_column_tests {
use super::ItemColumns;
use horizon_client::{entities::ItemEntity, items::ItemStack};
use horizon_core::geometry::Vec3;
fn item(id: u32, x: f64, y: f64, z: f64) -> ItemEntity {
let at = Vec3::new(x, y, z);
ItemEntity {
health: 5,
fire_ticks: 0,
id,
stack: ItemStack::new("minecraft:stone", 1),
thrower: None,
position: at,
previous: at,
velocity: Vec3::ZERO,
on_ground: true,
age: 0,
pickup_delay: 0,
bob_offset: 0.0,
ticks: 0,
}
}
/// `hopper_suck`'s test: some item box meets the hopper's SUCK_AABB.
fn scan(items: &[ItemEntity], (x, y, z): (i32, i32, i32)) -> bool {
let (min, max) = (
Vec3::new(f64::from(x), f64::from(y) + 11.0 / 16.0, f64::from(z)),
Vec3::new(f64::from(x) + 1.0, f64::from(y) + 2.0, f64::from(z) + 1.0),
);
items.iter().any(|i| {
let b = i.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
lo.x < max.x
&& hi.x > min.x
&& lo.y < max.y
&& hi.y > min.y
&& lo.z < max.z
&& hi.z > min.z
})
}
/// One tick of empty hoppers looking for items: each scans every item
/// (before) or asks the columns first (after, build included).
#[test]
#[ignore]
fn hopper_suck_cost() {
for (hoppers, count) in [(500i32, 200u32), (2000, 500), (2000, 2000)] {
let mut seed = 99u64;
let mut next = |range: f64| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
(seed >> 11) as f64 / (1u64 << 53) as f64 * range
};
let items: Vec<ItemEntity> = (0..count)
.map(|id| item(id, next(160.0), 64.0, next(160.0)))
.collect();
let at: Vec<(i32, i32, i32)> = (0..hoppers)
.map(|_| (next(160.0) as i32, 63, next(160.0) as i32))
.collect();
let t = std::time::Instant::now();
let a: Vec<bool> = at.iter().map(|&h| scan(&items, h)).collect();
let before = t.elapsed().as_secs_f64() * 1e3;
let t = std::time::Instant::now();
let mut columns = ItemColumns::default();
let b: Vec<bool> = at
.iter()
.map(|&h| columns.may_reach(&items, h.0, h.2) && scan(&items, h))
.collect();
let after = t.elapsed().as_secs_f64() * 1e3;
assert_eq!(a, b);
println!("{hoppers} hoppers, {count} items: {before:.3} ms -> {after:.3} ms");
}
}
#[test]
fn no_hopper_with_an_item_over_it_is_skipped() {
let mut seed = 0x1234_5678_9abc_def1u64;
let mut next = |range: f64| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
(seed >> 11) as f64 / (1u64 << 53) as f64 * range
};
let mut items: Vec<ItemEntity> = Vec::new();
let mut columns = ItemColumns::default();
let mut next_id = 0;
let mut skipped = 0;
for round in 0..3000 {
// Items come and go as hoppers take them and crafters drop them.
match round % 5 {
0 | 1 => {
next_id += 1;
// On edges too: a quarter of them sit on a block line.
let snap = |v: f64, edge: bool| if edge { v.floor() + 0.125 } else { v };
let edge = round % 4 == 0;
items.push(item(
next_id,
snap(next(24.0) - 12.0, edge),
64.0,
snap(next(24.0) - 12.0, edge),
));
}
2 if !items.is_empty() => {
let i = next(items.len() as f64) as usize;
items.remove(i);
}
_ => {}
}
let hopper = (next(26.0) as i32 - 13, 63, next(26.0) as i32 - 13);
let reach = columns.may_reach(&items, hopper.0, hopper.2);
let found = scan(&items, hopper);
assert!(
reach || !found,
"round {round}: skipped a hopper with an item over it"
);
skipped += usize::from(!reach);
}
assert!(skipped > 1000, "skipped only {skipped}");
}
}
@@ -8,6 +8,7 @@ use horizon_client::{
containers::Crafter,
hud::{HudBatch, rgba},
};
use horizon_protocol::packets::play::{self, Serverbound as S};
use serde_json::Value;
/// `CrafterBlock`'s crafting animation length.
@@ -323,6 +324,15 @@ impl Game<'_> {
menu.set_slot_state(i, enabled);
Some(true)
});
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.clone()) {
self.send(S::ContainerSlotStateChanged(
play::ContainerSlotStateChanged {
slot: i as i32,
container,
enabled,
},
));
}
let pitch = if enabled { 1.0 } else { 0.75 };
self.audio
.play("minecraft:ui.button.click", None, 0.4, pitch);
@@ -0,0 +1,110 @@
//! `PistonHeadRenderer`: while a piston moves them, blocks are
//! `minecraft:moving_piston` block entities (drawn as nothing by the chunk
//! mesher); this draws each moved block at its interpolated offset.
use super::Game;
use horizon_client::mesher::Vertex;
use horizon_world::{piston_shape::MovingPistonState, registry::BlockStateId};
impl Game<'_> {
/// `PistonHeadRenderer.extractRenderState` and `submit`.
pub(super) fn moving_piston_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<Vertex>,
) {
let partial = alpha as f32;
for &(p, piston) in &self.world.moving_pistons {
let Some((block, base)) = self.moving_piston_blocks(piston, partial) else {
continue;
};
let step = piston.movement_direction().normal();
let from = horizon_core::position::BlockPos::new(
p[0] - step[0],
p[1] - step[1],
p[2] - step[2],
);
let offset = piston.interpolated_offset(partial);
let light = self.world.light(p[0], p[1], p[2]);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let corner = glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]));
let moved = corner + glam::Vec3::from_array(offset).as_dvec3();
self.moving_block_vertices(block, from, moved - camera, packed, out);
if let Some(base) = base {
let at = horizon_core::position::BlockPos::new(p[0], p[1], p[2]);
self.moving_block_vertices(base, at, corner - camera, packed, out);
}
}
}
/// The moved block and, for a retracting piston, its extended base.
fn moving_piston_blocks(
&self,
piston: MovingPistonState,
partial: f32,
) -> Option<(BlockStateId, Option<BlockStateId>)> {
let facts = self.res.facts();
if facts.is_air(piston.moved_state) {
return None;
}
let progress = piston.interpolated_progress(partial);
let name = &*facts.get(piston.moved_state).name;
// Vanilla tests `progress <= 4.0`: a moving head is always drawn so.
if name == "minecraft:piston_head" {
let short = if progress <= 0.5 { "true" } else { "false" };
return Some((
self.with_props(piston.moved_state, &[("short", short)])?,
None,
));
}
if piston.source && !piston.extending {
let registry = &self.pack.assets.registry;
let facing = registry
.state(piston.moved_state)?
.properties
.get("facing")?
.clone();
let kind = if name == "minecraft:sticky_piston" {
"sticky"
} else {
"normal"
};
let short = if progress >= 0.5 { "true" } else { "false" };
let head = self.with_props(
registry.default_state("minecraft:piston_head")?,
&[("type", kind), ("facing", &facing), ("short", short)],
)?;
let base = self.with_props(piston.moved_state, &[("extended", "true")])?;
return Some((head, Some(base)));
}
Some((piston.moved_state, None))
}
/// One `MovingBlockRenderState`: the baked model at `at` (camera-relative),
/// seeded by its block position and tinted like a falling block.
fn moving_block_vertices(
&self,
state: BlockStateId,
seed: horizon_core::position::BlockPos,
at: glam::DVec3,
light: u32,
out: &mut Vec<Vertex>,
) {
let tint = self
.particle_sprite(state, [seed.x, seed.y, seed.z])
.map(|(_, tint)| tint);
let start = out.len();
self.block_model_vertices(
state,
horizon_core::random::position_seed(seed),
glam::Mat4::from_translation(at.as_vec3()),
light,
false,
out,
);
if let Some(tint) = tint {
let tint = horizon_client::mobs::render::abgr(tint);
for vertex in &mut out[start..] {
vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint);
}
}
}
}
@@ -9,6 +9,7 @@ use horizon_client::{
mobs::{
Mob, MobWorld, Species,
data::{self, MobData},
seen_grid::SeenGrid,
spawn_rules::{Dimension, SpawnLevel},
spawn_selection::{
self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest,
@@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> {
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
/// The types and boxes of what a spawner created this tick.
pub(super) pending_ids: std::cell::RefCell<Vec<(String, Aabb)>>,
/// The game's mobs by box, built once a pass has asked more than
/// [`SCANNED_QUERIES`] box queries (the mobs do not change while it
/// holds the game); the first ones scan, as the build costs a few scans.
pub(super) boxes: std::cell::OnceCell<MobBoxes>,
pub(super) box_queries: std::cell::Cell<u32>,
}
const SCANNED_QUERIES: u32 = 8;
/// A mob not removed: its index in `Game::mobs`, box, alive, and whether
/// it is a living shulker.
type MobBox = (usize, Aabb, bool, bool);
fn mob_box(i: usize, m: &Mob) -> MobBox {
let alive = m.alive();
(
i,
m.bounds(),
alive,
alive && m.species() == Species::Shulker,
)
}
/// The boxes of the game's mobs not removed, and a grid over them.
pub(super) struct MobBoxes {
entries: Vec<MobBox>,
grid: SeenGrid,
}
impl MobBoxes {
fn new(mobs: &[Mob]) -> Self {
let entries: Vec<_> = mobs
.iter()
.enumerate()
.filter(|(_, m)| !m.removed)
.map(|(i, m)| mob_box(i, m))
.collect();
let grid = SeenGrid::new(entries.iter().map(|e| e.1));
Self { entries, grid }
}
/// The entries whose boxes meet `area` (and possibly a few more).
fn near(&self, area: Aabb) -> impl Iterator<Item = MobBox> + '_ {
let mut near = Vec::new();
let indexed = self.grid.candidates(area, &mut near);
let all = (!indexed).then(|| self.entries.iter());
near.into_iter()
.map(|i| self.entries[i as usize])
.chain(all.into_iter().flatten().copied())
}
}
impl GameLevel<'_, '_> {
/// The mobs not removed whose boxes may meet `area` (callers test them).
fn mobs_near(&self, area: Aabb) -> Box<dyn Iterator<Item = MobBox> + '_> {
let asked = self.box_queries.get() + 1;
self.box_queries.set(asked);
if asked <= SCANNED_QUERIES && self.boxes.get().is_none() {
return Box::new(
self.game
.mobs
.iter()
.enumerate()
.filter(|(_, m)| !m.removed)
.map(|(i, m)| mob_box(i, m)),
);
}
Box::new(
self.boxes
.get_or_init(|| MobBoxes::new(&self.game.mobs))
.near(area),
)
}
fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> {
let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?;
Some(self.game.res.biomes().get(chunk.biome(x, y, z)))
@@ -191,7 +256,13 @@ impl NaturalLevel for GameLevel<'_, '_> {
StructureSpawns::shared(&self.game.options.resources)
}
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z))
// The nearest player's distance (`nearest_player`), without finding
// which player it is: every spawn attempt asks.
self.players
.iter()
.filter(|p| !p.spectator)
.map(|p| p.distance_sqr(x, y, z))
.reduce(f64::min)
}
fn respawn(&self) -> Option<[i32; 3]> {
// The world spawn point lives in the overworld.
@@ -218,12 +289,9 @@ impl NaturalLevel for GameLevel<'_, '_> {
// getEntityCollisions(null, box): living shulkers are solid.
let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7));
no_collision_empty(&mut scene, bounds)
&& !self.game.mobs.iter().any(|m| {
m.species() == Species::Shulker
&& m.alive()
&& !m.removed
&& m.bounds().intersects(grown)
})
&& !self
.mobs_near(grown)
.any(|(_, b, _, shulker)| shulker && b.intersects(grown))
&& !self
.pending_ids
.borrow()
@@ -238,10 +306,8 @@ impl NaturalLevel for GameLevel<'_, '_> {
!player
&& !self.pending.borrow().iter().any(|b| b.intersects(bounds))
&& !self
.game
.mobs
.iter()
.any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds))
.mobs_near(bounds)
.any(|(_, b, alive, _)| alive && b.intersects(bounds))
}
fn spawn_mobs(&self) -> bool {
self.game.ui.rules.bool("spawn_mobs")
@@ -283,10 +349,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> {
}
fn count_entities(&self, id: &str, bounds: Aabb) -> usize {
let mobs = self
.game
.mobs
.iter()
.filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds))
.mobs_near(bounds)
.filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds))
.count();
let pending = self
.pending_ids
@@ -305,6 +369,8 @@ impl<'a> Game<'a> {
players: self.level_players(),
pending: Default::default(),
pending_ids: Default::default(),
boxes: Default::default(),
box_queries: Default::default(),
}
}
/// Creates a mob the spawner accepted, finalized the game's way; the
@@ -1,8 +1,7 @@
//! `OminousItemSpawner`: the item an ominous trial spawner drops on its
//! fight. It floats, growing and turning (`OminousItemSpawnerRenderer`), for
//! 60 to 120 ticks, then falls as an item or is fired straight down as a
//! projectile (`spawnItem`). Not saved: a spawner left in an unloaded chunk
//! is lost.
//! projectile (`spawnItem`). Saved with its chunk's entities (persist.rs).
use super::Game;
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
@@ -22,10 +21,14 @@ const TICKS_SCALING: f32 = 50.0;
const ROTATION_SPEED: f32 = 40.0;
pub(super) struct OminousItemSpawner {
item: ItemStack,
position: [f64; 3],
spawn_item_after: i64,
pub(super) item: ItemStack,
pub(super) position: [f64; 3],
pub(super) spawn_item_after: i64,
tick_count: i64,
/// Its UUID, and the compound it was loaded from (fields Horizon doesn't
/// model survive a save).
pub(super) uuid: [i32; 4],
pub(super) raw: Option<Box<horizon_world::nbt::Tag>>,
}
/// `ProjectileItem.DispenseConfig` of the items fired down: power,
@@ -66,6 +69,26 @@ impl Game<'_> {
position,
spawn_item_after: i64::from(delay),
tick_count: 0,
uuid: horizon_client::save::random_uuid(),
raw: None,
});
}
/// A saved spawner, as `readAdditionalSaveData` leaves it: its tick
/// count starts again from 0.
pub(super) fn load_ominous_item_spawner(&mut self, tag: horizon_world::nbt::Tag) {
let Some((item, at, spawn_item_after)) =
horizon_client::entity_nbt::ominous_item_spawner_from_nbt(&tag)
else {
return;
};
self.ominous_spawners.push(OminousItemSpawner {
item,
position: [at.x, at.y, at.z],
spawn_item_after,
tick_count: 0,
uuid: horizon_client::entity_nbt::uuid(&tag)
.unwrap_or_else(horizon_client::save::random_uuid),
raw: Some(Box::new(tag)),
});
}
/// Every item spawner's tick: `commonTick`'s count, `tickServer` (the
@@ -230,6 +230,11 @@ impl Game<'_> {
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
Event::OpenShaderPackFolder => {
let dir = horizon_client::shader_pack::folder();
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
}
}
Ok(())
+16
View File
@@ -274,6 +274,7 @@ impl Game<'_> {
self.carts.push(c);
}
}
"minecraft:ominous_item_spawner" => self.load_ominous_item_spawner(tag),
"minecraft:ender_dragon" => {
let seed = self.world.random.next_long();
if self.dragon.is_none()
@@ -685,6 +686,19 @@ impl Game<'_> {
.push(c.to_nbt(uuid, raw.as_ref()));
}
}
for s in &self.ominous_spawners {
let at = Vec3::new(s.position[0], s.position[1], s.position[2]);
if keys.contains(&chunk_of(at)) {
let tag = entity_nbt::ominous_item_spawner_to_nbt(
&s.item,
at,
s.spawn_item_after,
s.uuid,
s.raw.as_deref(),
);
out.entry(chunk_of(at)).or_default().push(tag);
}
}
for c in &self.carts {
if keys.contains(&chunk_of(c.position)) {
let uuid = self
@@ -774,6 +788,8 @@ impl Game<'_> {
keep
});
self.crystals.retain(|c| !gone(c.position));
self.ominous_spawners
.retain(|s| !gone(Vec3::new(s.position[0], s.position[1], s.position[2])));
if self.dragon.as_ref().is_some_and(|d| gone(d.position)) {
self.dragon = None;
}
+53 -1
View File
@@ -223,6 +223,14 @@ impl Game<'_> {
.riding
.and_then(|id| self.mobs.iter().find(|m| m.id == id))
.map(|_| (1.0, 4.0));
// AbstractBoat.positionRider turns a passenger by the boat's
// deltaRotation after its yRotO was saved, and LocalPlayer.getViewYRot
// interpolates a passenger's yaw: the boat's turn is spread over the
// frames of a tick.
let ride_turn = self
.riding
.and_then(|id| self.boats.iter().find(|b| b.id == id))
.map_or(0.0, |b| b.delta_rotation);
let entity = CameraEntity {
position: [p.position.x, p.position.y, p.position.z],
previous: [
@@ -235,7 +243,7 @@ impl Game<'_> {
x_rot: self.pitch,
y_rot: self.yaw,
x_rot_o: self.pitch,
y_rot_o: self.yaw,
y_rot_o: self.yaw - ride_turn,
eye_height: p.dimensions.eye_height,
living: Some(LivingCamera {
scale,
@@ -304,6 +312,7 @@ impl Game<'_> {
let crouching = p.pose == Pose::Crouching;
let (position, flying) = (p.position, p.flying || p.fall_flying);
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
let spinning = p.auto_spin_attack_ticks > 0;
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
let using_off_hand = self
.using
@@ -389,6 +398,7 @@ impl Game<'_> {
m.velocity = velocity;
m.extra.fall_flying = fall_flying;
m.extra.fall_fly_ticks = fly_ticks;
m.extra.auto_spin_attack = spinning;
m.extra.main_hand_left = self.settings.main_hand_left;
m.extra.using_item = using;
m.extra.using_off_hand = using_off_hand;
@@ -443,6 +453,7 @@ impl Game<'_> {
out,
);
self.player_elytra_geometry(m, camera, alpha as f32, packed, out);
self.spin_attack_geometry(m, camera, alpha as f32, packed, out);
self.held_item_geometry(m, camera, alpha, packed, true, out);
}
/// `extractEntityInInventoryFollowsMouse`: the player in the box
@@ -584,6 +595,47 @@ impl Game<'_> {
out,
);
}
/// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning
/// player (`SpinAttackEffectModel.setupAnim`).
fn spin_attack_geometry(
&self,
m: &Mob,
camera: glam::DVec3,
partial: f32,
light: u32,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
if !m.extra.auto_spin_attack {
return;
}
let (Some(model), Some(rect)) = (
self.res.spin_attack().as_ref(),
self.gui.atlas.sprites.get("entity/trident/trident_riptide"),
) else {
return;
};
let age = m.age as f32 + partial;
horizon_client::mobs::render_model(
model,
horizon_client::mobs::render::base_transform(m, partial, camera),
&|part| {
let mut p = part.pose;
if let Some(i) = part
.name
.strip_prefix("box")
.and_then(|i| i.parse::<u8>().ok())
{
let angle = age * -(45.0 + f32::from(i + 1) * 5.0);
p[4] = wrap(angle).to_radians();
}
p
},
[rect.u0, rect.v0, rect.u1, rect.v1],
light,
0,
out,
);
}
}
fn player_preview_quads(
+35 -6
View File
@@ -6,7 +6,7 @@ use horizon_client::{
items::ItemStack,
mobs::{Species, Who, piglin::ADMIRE},
};
use horizon_core::random::RandomSource;
use horizon_core::{geometry::Vec3, random::RandomSource};
impl Game<'_> {
fn piglin_loved(&self, item: &str) -> bool {
@@ -34,6 +34,9 @@ impl Game<'_> {
if !self.ui.rules.bool("mob_griefing") {
return;
}
// Whether each item is piglin-loved, kept until an item is added or
// removed (added ones are pushed at the end under a new id).
let mut loved: (Option<(usize, Option<u32>)>, Vec<bool>) = (None, Vec::new());
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Piglin
@@ -46,11 +49,20 @@ impl Game<'_> {
continue;
}
let pos = m.position;
let key = (self.dropped.len(), self.dropped.last().map(|e| e.id));
if loved.0 != Some(key) {
loved.0 = Some(key);
loved.1 = self
.dropped
.iter()
.map(|e| self.piglin_loved(&e.stack.item))
.collect();
}
let best = self
.dropped
.iter()
.enumerate()
.filter(|(_, e)| self.piglin_loved(&e.stack.item))
.filter(|&(j, _)| loved.1[j])
.map(|(j, e)| (j, e.position.distance_squared(pos)))
.filter(|(_, d)| *d <= 81.0)
.min_by(|a, b| a.1.total_cmp(&b.1));
@@ -132,12 +144,29 @@ impl Game<'_> {
} else {
vec![ItemStack::new(&item, 1)]
};
// BehaviorUtils.throwItem toward the nearest visible player, else nearby.
let target = self
// BehaviorUtils.throwItem toward the nearest visible player
// (NEAREST_VISIBLE_PLAYER: within 16, alive, no spectators; the
// guests count as much as the host), else nearby.
let at = m.position;
let host = self
.player
.as_ref()
.filter(|p| p.position.distance_squared(m.position) < 256.0)
.map(|p| [p.position.x, p.position.y + 1.0, p.position.z]);
.filter(|p| !p.health.dead_or_dying() && !self.spectator())
.map(|p| [p.position.x, p.position.y, p.position.z]);
let guests = self.lan.iter().flat_map(|h| {
h.hub
.guests
.iter()
.filter(|g| h.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| g.position)
});
let d = |p: &[f64; 3]| at.distance_squared(Vec3::new(p[0], p[1], p[2]));
let target = host
.into_iter()
.chain(guests)
.filter(|p| d(p) < 256.0)
.min_by(|a, b| d(a).total_cmp(&d(b)))
.map(|p| [p[0], p[1] + 1.0, p[2]]);
for stack in items {
let to = target.unwrap_or_else(|| {
let r = &mut self.world.random;
+53 -23
View File
@@ -2,13 +2,16 @@
//! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`),
//! filling glass bottles (`BottleItem`), the per-tick effect application,
//! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`).
use super::{Game, Screen};
use super::{Game, Screen, item_draw::owner_at};
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
block_entity_render::vertex_light,
brewing,
effects::{EffectAction, EffectInstance, PlayerEffects},
hud::HudBatch,
hud_layout, hud_overlays, inventory_effects,
items::ItemStack,
mesher::Vertex,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
@@ -16,6 +19,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource};
#[derive(Clone, Debug)]
pub(super) struct ThrownPotion {
stack: ItemStack,
/// The position before the last tick, for drawing between ticks.
previous: Vec3,
position: Vec3,
velocity: Vec3,
age: u32,
@@ -43,6 +48,7 @@ impl Game<'_> {
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
self.potions.thrown.push(ThrownPotion {
stack,
previous: position,
position,
velocity,
age: 0,
@@ -411,6 +417,7 @@ impl Game<'_> {
let mut landed = Vec::new();
thrown.retain_mut(|t| {
t.age += 1;
t.previous = t.position;
let next = Vec3::new(
t.position.x + t.velocity.x,
t.position.y + t.velocity.y,
@@ -461,33 +468,56 @@ impl Game<'_> {
);
t.age < 1200 && t.position.y > -128.0
});
// ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position.
for t in &thrown {
let sprite = match &*t.stack.item {
"minecraft:lingering_potion" => "item/lingering_potion",
"minecraft:experience_bottle" => "item/experience_bottle",
_ => "item/splash_potion",
};
let mut fixed = horizon_core::random::LegacyRandom::new(0);
let mut p = horizon_client::particles::Particle::terrain(
&mut fixed,
[t.position.x, t.position.y, t.position.z],
[0.0; 3],
sprite.into(),
0xFFFFFF,
);
p.velocity = [0.0; 3];
p.gravity = 0.0;
p.lifetime = 2;
p.size = 0.25;
p.uv = [0.0, 0.0, 1.0, 1.0];
self.particles.push(p);
}
self.potions.thrown = thrown;
for (stack, at) in landed {
self.splash(&stack, at);
}
}
/// `ThrownItemRenderer` for thrown splash and lingering potions and
/// experience bottles: the item (GROUND) facing the camera at scale 1,
/// lit at the light probe (the eye, 0.85 of the 0.25 height).
pub(super) fn thrown_potion_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<Vertex>,
) {
let orientation = glam::Mat4::from_quat(self.camera_orientation());
for t in &self.potions.thrown {
let previous = glam::DVec3::new(t.previous.x, t.previous.y, t.previous.z);
let position = glam::DVec3::new(t.position.x, t.position.y, t.position.z);
// ThrowableProjectile.shouldRenderAtSqrDistance: hidden for its
// first two ticks within 3.5 blocks (not in the thrower's face).
if t.age < 2 && position.distance_squared(camera) < 12.25 {
continue;
}
if !self.standing_entity_in_view(
camera,
super::entity_culling::at(t.previous),
super::entity_culling::at(t.position),
alpha,
0.25,
0.25,
64.0,
0.0,
) {
continue;
}
let p = previous.lerp(position, alpha);
let owner = owner_at(p.to_array(), 0.0, &t.stack.item);
let state = self.resolve_item(&t.stack, DisplayContext::Ground, Some(&owner), 0);
if state.is_empty() {
continue;
}
let pose = glam::Mat4::from_translation((p - camera).as_vec3()) * orientation;
let light = self.world.light(
p.x.floor() as i32,
(p.y + 0.2125).floor() as i32,
p.z.floor() as i32,
);
self.submit_item_world(&state, pose, vertex_light(light), out);
}
}
/// A splash potion's effects on the player in place, by their distance.
fn splash_on_player(
&mut self,
@@ -279,7 +279,11 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: None,
maps: None,
};
for i in 0..36 {
menu.set_player_item(i, self.inventory[i].clone());
+405 -30
View File
@@ -41,7 +41,11 @@ use horizon_protocol::{
text::{Language, format_java, plain},
};
use horizon_world::{nbt::Tag, registry::BlockStateId};
use std::{collections::HashMap, sync::Arc, time::Instant};
use std::{
collections::{HashMap, VecDeque},
sync::Arc,
time::{Duration, Instant},
};
use winit::{event::MouseButton, keyboard::KeyCode};
/// A text component the server sent, for the HUD.
@@ -99,6 +103,10 @@ pub(super) struct Remote {
last_input: u8,
was_sprinting: bool,
carried: Option<usize>,
/// The last ClientboundPlayerAbilitiesPacket. Vanilla's LocalPlayer
/// holds its abilities from the login on; here the player is made at
/// the first teleport, which takes them then.
abilities: Option<play::PlayerAbilities>,
loaded_sent: bool,
/// The view distance last sent in ClientInformation.
sent_view: i8,
@@ -108,9 +116,9 @@ pub(super) struct Remote {
/// only replace the remembered state; then the block takes it.
predictions: HashMap<[i32; 3], (i32, i32)>,
/// Open container: (window id, menu name).
menu: Option<(i32, String)>,
pub(super) menu: Option<(i32, String)>,
/// The open menu's title as the server named it.
menu_title: Option<String>,
pub(super) menu_title: Option<String>,
state_id: i32,
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
@@ -158,8 +166,22 @@ pub(super) struct Remote {
clock_game_time: i64,
/// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket).
chunk_center: (i32, i32),
/// Received events a frame left for the next one, in order, and when
/// the oldest of them first waited (`poll_remote`).
backlog: VecDeque<Event>,
backlog_since: Option<Instant>,
}
/// The time a frame spends on chunk packets before it leaves the rest of
/// the received events for the next frame. A batch of 25 to 60 columns
/// (0.1 ms each on an M4 Pro) all in one frame was a 3 to 8 ms frame every
/// time the player crossed a chunk border at 32 chunks.
const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1);
/// Events that have waited this long are all handled in the next frame,
/// whatever their cost: the packets after a slow machine's chunks never
/// wait more than a tick.
const BACKLOG_LIMIT: Duration = Duration::from_millis(50);
fn face_direction(face: [i32; 3]) -> u8 {
match face {
[0, -1, 0] => 0,
@@ -313,6 +335,7 @@ impl Game<'_> {
last_input: 0,
was_sprinting: false,
carried: None,
abilities: None,
loaded_sent: false,
sent_view: view,
predictions: HashMap::new(),
@@ -350,6 +373,8 @@ impl Game<'_> {
clock_partial: 0.0,
clock_game_time: 0,
chunk_center: (0, 0),
backlog: VecDeque::new(),
backlog_since: None,
});
// The level's TickRateManager follows the server's ticking packets.
self.clock = horizon_client::clock::FixedStep::client();
@@ -446,8 +471,15 @@ impl Game<'_> {
.unwrap_or("minecraft:air"),
)
}
/// The server's network id of a mob effect (`brewing::EFFECTS` id).
pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option<i32> {
let r = self.remote.as_ref()?;
r.builtin
.get("minecraft:mob_effect")?
.id(&format!("minecraft:{effect}"))
}
/// A mob effect's network id as the effect (`brewing::EFFECTS` id).
fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
let r = self.remote.as_ref()?;
let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?;
horizon_client::brewing::effect(name).map(|d| d.id)
@@ -493,6 +525,54 @@ impl Game<'_> {
if let Some(Component::Int(id)) = s.component(component::MAP_ID) {
out.data_mut().map_id = Some(*id);
}
if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) {
out.data_mut().repair_cost = (*cost).max(0) as u32;
}
if let Some(Component::Int(mode)) = s.component(component::MAP_POST_PROCESSING) {
out.data_mut().map_post_processing = Some((*mode).clamp(0, 1) as u8);
}
if let Some(Component::WritableBook(pages)) = s.component(component::WRITABLE_BOOK_CONTENT)
{
out.data_mut().writable_pages = pages.clone();
}
if let Some(Component::WrittenBook(b)) = s.component(component::WRITTEN_BOOK_CONTENT) {
let lang = self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default();
out.data_mut().written = Some(horizon_client::item_data::WrittenBook {
title: b.title.clone(),
author: b.author.clone(),
generation: b.generation.clamp(0, 3) as u8,
pages: b.pages.iter().map(|p| plain(p, &lang)).collect(),
});
}
if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) {
let lang = self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default();
out.data_mut().custom_name = Some(plain(name, &lang));
}
// The enchantments by the server's registry ids.
let levels = |list: &[(i32, i32)]| -> Vec<(Arc<str>, u32)> {
let names = self.remote.as_ref().map(|r| &r.registries);
list.iter()
.filter_map(|(id, level)| {
let name = names?.name("minecraft:enchantment", *id)?;
Some((Arc::from(name), (*level).max(0) as u32))
})
.collect()
};
if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) {
out.data_mut().enchantments = levels(list);
}
if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) {
out.data_mut().stored_enchantments = levels(list);
}
out.tidy();
Some(out)
}
fn to_network(&self, s: &Option<ItemStack>) -> Option<Stack> {
@@ -524,6 +604,28 @@ impl Game<'_> {
}
}
/// The minecarts the server sent, for the control socket's `status`
/// (their velocity is not tracked here).
pub(super) fn remote_carts(&self) -> Option<Vec<serde_json::Value>> {
let r = self.remote.as_ref()?;
let mut carts: Vec<&Tracked> = r
.entities
.values()
.filter(|t| t.kind.ends_with("minecart"))
.collect();
carts.sort_by(|a, b| {
a.position
.partial_cmp(&b.position)
.unwrap_or(std::cmp::Ordering::Equal)
});
Some(
carts
.into_iter()
.map(|t| serde_json::json!({"kind": t.kind, "position": t.position, "velocity": [0.0, 0.0, 0.0]}))
.collect(),
)
}
/// The names in the server's player list, sorted.
pub(super) fn remote_online_names(&self) -> Option<Vec<String>> {
let r = self.remote.as_ref()?;
@@ -544,12 +646,34 @@ impl Game<'_> {
Some(r.chat.iter().rev().take(n).map(|l| l.0.clone()).collect())
}
/// Process everything the network thread received (once per frame, like
/// the client's packet processor).
/// Received events left for the next frame (`poll_remote`): until they
/// are handled, the terrain the server sent is not all there.
pub(super) fn remote_backlog(&self) -> usize {
self.remote.as_ref().map_or(0, |r| r.backlog.len())
}
/// Process what the network thread received (once per frame, like the
/// client's packet processor), in order. Chunk packets get
/// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from
/// the next chunk packet on wait for the next frame, unless they have
/// already waited `BACKLOG_LIMIT`.
pub(super) fn poll_remote(&mut self) -> Result<()> {
let Some(r) = &self.remote else { return Ok(()) };
let events = r.session.poll();
for event in events {
let Some(r) = self.remote.as_mut() else {
return Ok(());
};
let mut events = std::mem::take(&mut r.backlog);
events.extend(r.session.poll());
let overdue = r
.backlog_since
.is_some_and(|since| since.elapsed() >= BACKLOG_LIMIT);
let mut chunks = Duration::ZERO;
while let Some(event) = events.pop_front() {
let chunk =
matches!(&event, Event::Packet(p) if matches!(**p, C::LevelChunkWithLight(_)));
if chunk && !overdue && chunks >= CHUNK_PACKETS_PER_FRAME {
events.push_front(event);
break;
}
let started = chunk.then(Instant::now);
match event {
Event::Status(s) => {
if let Some(r) = self.remote.as_mut() {
@@ -595,10 +719,19 @@ impl Game<'_> {
}
Event::Packet(packet) => self.handle_packet(*packet)?,
}
chunks += started.map_or(Duration::ZERO, |t| t.elapsed());
if self.remote.is_none() {
break;
}
}
if let Some(r) = self.remote.as_mut() {
r.backlog_since = if events.is_empty() {
None
} else {
Some(r.backlog_since.unwrap_or_else(Instant::now))
};
r.backlog = events;
}
self.send_suggestion_request();
Ok(())
}
@@ -1216,9 +1349,39 @@ impl Game<'_> {
"minecraft:hopper" => slots(5),
"minecraft:generic_3x3" => slots(9),
"minecraft:brewing_stand" => slots(5),
_ => None,
// CrafterMenu: the grid, the inventory, then the result (the
// client's own).
"minecraft:crafter_3x3" => slots(9),
// A workstation: its inputs, its result, then the inventory.
m => {
let kind = Self::remote_station_kind(m)?;
let inputs = kind.inputs();
let own = inputs + usize::from(kind.has_result());
match s {
_ if s < inputs => Some(super::stations::INPUT + s),
_ if s < own => Some(super::stations::RESULT),
_ if s < own + 27 => Some(9 + s - own),
_ if s < own + 36 => Some(s - own - 27),
_ => None,
}
}
}
}
/// The workstation screen of a menu type a server opens.
pub(super) fn remote_station_kind(menu: &str) -> Option<super::stations::Kind> {
use super::stations::Kind;
Some(match menu {
"minecraft:loom" => Kind::Loom,
"minecraft:stonecutter" => Kind::Stonecutter,
"minecraft:grindstone" => Kind::Grindstone,
"minecraft:anvil" => Kind::Anvil,
"minecraft:smithing" => Kind::Smithing,
"minecraft:enchantment" => Kind::Enchanting,
"minecraft:beacon" => Kind::Beacon,
"minecraft:cartography_table" => Kind::Cartography,
_ => return None,
})
}
fn open_menu_name(&self, container: i32) -> String {
match self.remote.as_ref().and_then(|r| r.menu.as_ref()) {
Some((id, name)) if *id == container && container != 0 => name.clone(),
@@ -1227,6 +1390,12 @@ impl Game<'_> {
}
fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option<ItemStack>) {
let menu = self.open_menu_name(container);
if menu == "minecraft:lectern" {
if slot == 0 {
self.remote_lectern_book(item);
}
return;
}
if container != 0 && menu == "inventory" {
return;
}
@@ -1237,6 +1406,9 @@ impl Game<'_> {
return; // the result slot is recomputed from the grid
}
*self.slot_mut(internal) = item;
if internal >= super::stations::INPUT && self.station.is_some() {
self.remote_station_slot_changed(internal);
}
}
fn handle_packet(&mut self, packet: C) -> Result<()> {
@@ -1342,6 +1514,10 @@ impl Game<'_> {
}));
}
C::BlockUpdate(p) => self.server_block(p.pos, p.state),
// ClientPacketListener.handleBlockDestruction: another player's crack.
C::BlockDestruction(p) => {
self.destroy_block_progress(p.id, p.pos, i32::from(p.progress));
}
C::SectionBlocksUpdate(p) => {
let [sx, sy, sz] = p.section;
for change in p.changes {
@@ -1544,6 +1720,18 @@ impl Game<'_> {
}
}
}
// LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): another
// player lies down in their bed (drawn lying in it), or gets up.
if other {
for (index, _, value) in &p.values {
if let (14, Value::OptPos(bed)) = (index, value) {
let code = bed.map_or(0, |b| self.bed_facing(b));
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
m.extra.ints[1] = code;
}
}
}
}
// LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this
// player lies down in the bed, or gets up.
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
@@ -1824,9 +2012,10 @@ impl Game<'_> {
},
C::PlayerAbilities(p) => {
self.creative = p.flags & 8 != 0;
if let Some(player) = &mut self.player {
player.flying_speed = p.flying_speed;
if let Some(r) = self.remote.as_mut() {
r.abilities = Some(p);
}
self.apply_remote_abilities();
}
C::SetHeldSlot(p) => {
self.selected = p.slot.clamp(0, 8) as usize;
@@ -1865,6 +2054,12 @@ impl Game<'_> {
}
self.remote_synced();
}
C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => {
self.remote_lectern_page(i32::from(p.value));
}
C::ContainerSetData(p) if self.remote_station_open(p.container) => {
self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value);
}
C::ContainerSetData(p) => {
let v = i32::from(p.value);
match self
@@ -1878,6 +2073,12 @@ impl Game<'_> {
3 => f.cooking_total = v,
_ => {}
},
// CrafterBlockEntity.containerData.
Some(BlockEntity::Crafter(c)) => match usize::try_from(p.id) {
Ok(k @ 0..9) => c.disabled[k] = v == 1,
Ok(9) => c.triggered = v == 1,
_ => {}
},
// BrewingStandBlockEntity.dataAccess.
Some(BlockEntity::Brewing(b)) => match p.id {
0 => b.brew_time = v,
@@ -1895,6 +2096,7 @@ impl Game<'_> {
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p),
C::MerchantOffers(p) => self.remote_merchant_offers(p),
C::ContainerClose(_) if self.remote_lectern_closed() => {}
C::ContainerClose(_) => {
if self.screen == Screen::Inventory {
self.remote_close_local();
@@ -2469,6 +2671,7 @@ impl Game<'_> {
self.previous_eye = 1.62;
self.clock.reset();
self.apply_remote_health();
self.apply_remote_abilities();
}
}
self.previous_position = position;
@@ -2604,6 +2807,7 @@ impl Game<'_> {
[player.velocity.x, player.velocity.y, player.velocity.z],
[player.position.x, player.position.y, player.position.z],
);
let was_flying = player.flying;
player.yaw = self.yaw;
let dead = self.screen == Screen::Dead;
// LivingEntity.isImmobile: a sleeper lies still in the bed.
@@ -2626,6 +2830,9 @@ impl Game<'_> {
}
.controlled_simulation_tick(keys)?;
}
// LocalPlayer.onUpdateAbilities: flight turned on or off (a double
// jump, a spectator, landing) is sent to the server.
let flying = player.flying;
let events = std::mem::take(&mut player.events);
self.previous_eye = self.eye;
self.eye += (player.dimensions.eye_height - self.eye) * 0.5;
@@ -2660,9 +2867,29 @@ impl Game<'_> {
if !dead {
self.remote_tick_using();
}
if flying != was_flying {
self.send(S::PlayerAbilities(play::PlayerAbilitiesRequest {
flags: if flying { 2 } else { 0 },
}));
}
self.remote_send_state(input);
Ok(())
}
/// ClientPacketListener.handlePlayerAbilities: the player flies, may fly
/// and is invulnerable as the server says (bits 2, 4 and 1).
fn apply_remote_abilities(&mut self) {
let (Some(player), Some(a)) = (
self.player.as_mut(),
self.remote.as_ref().and_then(|r| r.abilities.as_ref()),
) else {
return;
};
player.invulnerable = a.flags & 1 != 0;
player.flying = a.flags & 2 != 0;
player.may_fly = a.flags & 4 != 0;
player.flying_speed = a.flying_speed;
}
/// The local player's share of every touching entity's
/// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy`
/// lets entities push only the local player, so the server never sends
@@ -3228,7 +3455,11 @@ impl Game<'_> {
.and_then(|h| self.res.items().get(&h.item))
.is_some_and(|i| i.block.is_some());
if let Some(hit) = self.pick() {
let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref());
let (reacts, changes) = if hand == Hand::Main {
self.remote_block_reacts(&hit, held.as_ref())
} else {
(false, DryUse::default())
};
let seq = self.next_sequence();
let cursor = [
(hit.point[0] - f64::from(hit.pos[0])) as f32,
@@ -3254,6 +3485,9 @@ impl Game<'_> {
r.use_target = Some(hit.pos);
r.placing = Some((target, ticks));
}
if reacts {
self.predict_use(&changes, seq);
}
if held_block {
self.with_hand(hand, Game::swing_arm);
return true;
@@ -3263,15 +3497,61 @@ impl Game<'_> {
false
}
/// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the
/// use changed on this client's level at once, each kept as predicted
/// under the use's sequence until the server acknowledges it (a use the
/// server refused goes back). Only the blocks a hand opens or flips: a
/// wooden or copper door, trapdoor or fence gate, a lever or a button;
/// whatever else the use changes waits for the server.
fn predict_use(&mut self, (changes, sounds): &DryUse, seq: i32) {
let facts = self.res.facts();
let predicted = |state: BlockStateId| hand_operated(&facts.get(state).name);
if changes.is_empty()
|| !changes
.iter()
.all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z)))
{
return;
}
for &(p, state) in changes {
let pos = [p.x, p.y, p.z];
let before = self.world.block(p.x, p.y, p.z);
// BlockStatePredictionHandler.retainKnownServerState.
if let Some(r) = self.remote.as_mut() {
r.predictions
.entry(pos)
.and_modify(|e| e.0 = seq)
.or_insert((seq, before.0 as i32));
}
self.set_block(pos, state.0 as i32);
}
// `level.playSound(player, ...)`: the clicker hears it from its own use; the
// server sends it to the others only.
for (pos, sound, volume, pitch) in sounds {
let at = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 0.5,
f64::from(pos.z) + 0.5,
];
let name = if sound.contains(':') {
sound.to_string()
} else {
format!("minecraft:{sound}")
};
self.audio.play(&name, Some(at), *volume, *pitch);
}
}
/// Whether the block hit takes a main-hand right click with `held`
/// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a
/// container. Vanilla's client runs it on its own level first; this runs
/// it on a copy that keeps no change.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool {
/// container, and the blocks it changed. Vanilla's client runs it on its
/// own level first; this runs it on a copy, and `predict_use` keeps the
/// changes it predicts.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) {
// Player.isSecondaryUseActive with something in either hand.
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
if self.keys.contains(&KeyCode::ShiftLeft) && hands_full {
return false;
return (false, DryUse::default());
}
use horizon_core::geometry::Direction;
let face = match hit.face {
@@ -3286,8 +3566,10 @@ impl Game<'_> {
world: &self.world,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
};
self.res
let reacts = self
.res
.behaviours()
.use_item_on(
&mut level,
@@ -3298,7 +3580,8 @@ impl Game<'_> {
self.use_context(),
held.map(|s| &*s.item),
)
.consumes_action()
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
@@ -3320,6 +3603,16 @@ impl Game<'_> {
// MultiPlayerGameMode.useItem runs the use here too: food starts
// being eaten (Consumable.startConsuming).
self.with_hand(hand, |g| g.start_eating(&info));
// BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting
// go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots.
if &*held.item == "minecraft:bow" {
self.with_hand(hand, |g| {
if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some())
{
g.using = Some((g.held_slot(), 0));
}
});
}
item_has_use(&info)
}
@@ -3335,14 +3628,20 @@ impl Game<'_> {
}
self.remote_use_item(Hand::Off);
}
/// `LivingEntity.updatingUsingItem` for a consumable on a server client: the
/// eating animation and its crumbs. The server eats it and sends the
/// stack, the hunger and the sounds.
/// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a
/// consumable's eating animation and its crumbs. The server eats it and
/// sends the stack, the hunger and the sounds.
fn remote_tick_using(&mut self) {
let Some((slot, ticks)) = self.using else {
return;
};
let stack = self.stack_in(slot).cloned();
// A drawn bow: held until the button lets go (or another slot is picked).
if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") {
self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT)
.then_some((slot, ticks + 1));
return;
}
let consumable = stack
.as_ref()
.and_then(|s| self.res.items().get(&s.item))
@@ -3452,7 +3751,18 @@ impl Game<'_> {
return true;
}
let mut instant = false;
if let Some((i, distance)) = self.mob_hit()
// A ghast's fireball or a wind charge nearer than any mob: the
// server turns it (game/deflect.rs).
if let Some((i, distance)) = self.redirectable_hit()
&& self.mob_hit().is_none_or(|(_, d)| distance <= d)
&& self.before_block(distance)
&& self.creatures.projectiles[i].id != 0
{
self.send(S::Attack(play::Attack {
id: self.creatures.projectiles[i].id as i32,
}));
self.reset_attack_strength();
} else if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
self.send(S::Attack(play::Attack {
@@ -3633,6 +3943,10 @@ impl Game<'_> {
/// engine doesn't model sends the clicks unpredicted. False when a click's
/// slot isn't one of the menu's.
pub(super) fn remote_menu_ops(&mut self, ops: &[(Option<usize>, i32, Input)]) -> bool {
// CrafterScreen.slotClicked: a slot toggle goes out before the click.
if let [(Some(slot), button, input)] = ops {
self.crafter_slot_clicked(*slot, *button, *input);
}
let (container, menu) = self.remote_menu();
let mut clicks = Vec::with_capacity(ops.len());
for &(slot, button, input) in ops {
@@ -3785,13 +4099,8 @@ impl Game<'_> {
r.menu = None;
r.menu_title = None;
}
if self
.station
.as_ref()
.is_some_and(|s| s.kind == super::stations::Kind::Merchant)
{
self.station = None;
}
// The client's menu has no level access: what it holds is the server's.
self.station = None;
self.craft_size = 2;
if let Some(key) = self.container.take() {
// Server containers stay renderable but lose their copied slots.
@@ -3865,6 +4174,27 @@ impl Game<'_> {
.as_ref()
.and_then(|r| r.use_target)
.map(|t| (t[0], t[1], t[2]));
if menu == "minecraft:lectern" {
// LecternScreen: the book and page come in the menu's content and data.
if let Some(r) = self.remote.as_mut() {
r.menu = Some((p.container, menu));
}
self.remote_open_lectern(target.unwrap_or_default());
return;
}
if let Some(kind) = Self::remote_station_kind(&menu) {
let title = plain(
&p.title,
&self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default(),
);
let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]);
self.remote_open_station(p.container, menu, kind, title, pos);
return;
}
if menu == "minecraft:merchant" {
// A trading window: its offers follow in a MerchantOffers packet.
let title = plain(
@@ -3904,6 +4234,8 @@ impl Game<'_> {
horizon_client::brewing::BrewingStand::new(),
))),
"minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])),
// CrafterMenu: the disabled slots and triggered come in ContainerSetData.
"minecraft:crafter_3x3" => Some(BlockEntity::Crafter(Default::default())),
m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => {
let rows = m
.strip_prefix("minecraft:generic_9x")
@@ -4102,6 +4434,13 @@ impl Game<'_> {
.filter(|m| r.level_players.contains_key(&(m.id as i32)) && !m.alive())
.map(|m| m.id)
.collect::<Vec<_>>(),
// The other players this client draws lying in a bed (SLEEPING_POS).
"lying_players": self
.mobs
.iter()
.filter(|m| r.level_players.contains_key(&(m.id as i32)) && m.extra.ints[1] != 0)
.map(|m| m.id)
.collect::<Vec<_>>(),
// The player's own model exists (third person and the inventory draw it).
"player_model": self.player_model.is_some(),
"health": r.health.0,
@@ -4193,9 +4532,45 @@ struct DryLevel<'w> {
world: &'w horizon_client::world::World,
changed: HashMap<horizon_core::position::BlockPos, BlockStateId>,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
sounds: Vec<DrySound>,
}
type DrySound = (
horizon_core::position::BlockPos,
std::sync::Arc<str>,
f32,
f32,
);
/// What a use on the dry level changed, and the sounds it played.
type DryUse = (
Vec<(horizon_core::position::BlockPos, BlockStateId)>,
Vec<DrySound>,
);
/// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or
/// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has
/// no hand use.
pub(super) fn hand_operated(name: &str) -> bool {
let name = name.trim_start_matches("minecraft:");
((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_"))
|| name.ends_with("_fence_gate")
|| name.ends_with("_button")
|| name == "lever"
}
impl horizon_world::level::LevelAccess for DryLevel<'_> {
fn emit(&mut self, event: horizon_world::level::LevelEvent) {
if let horizon_world::level::LevelEvent::Sound {
pos,
sound,
volume,
pitch,
} = event
{
self.sounds.push((pos, sound, volume, pitch));
}
}
fn block_state(&self, pos: horizon_core::position::BlockPos) -> BlockStateId {
self.changed
.get(&pos)
@@ -0,0 +1,156 @@
//! A server's workstation menus on this client: the server opens the menu
//! (`ClientboundOpenScreenPacket` with the station's `MenuType`), the
//! station screen draws it, and its clicks and buttons are predicted on the
//! menu engine (`Game::menu_session`) and sent, as
//! `MultiPlayerGameMode.handleContainerInput` and `handleInventoryButtonClick`
//! do. The menu's client-side `slotsChanged` follows the server's slots, and
//! its data slots come in `ClientboundContainerSetDataPacket`.
use super::{
Game, Screen,
stations::{Kind, Station},
};
use horizon_protocol::packets::play::{self, Serverbound as S};
impl Game<'_> {
/// The server opened workstation menu `menu` in window `container`.
pub(super) fn remote_open_station(
&mut self,
container: i32,
menu: String,
kind: Kind,
title: String,
pos: [i32; 3],
) {
if let Some(r) = self.remote.as_mut() {
r.menu = Some((container, menu));
r.menu_title = Some(title);
}
self.craft_size = 2;
self.container = None;
self.station = Some(Station::new_kind(kind, pos));
self.screen = Screen::Inventory;
self.capture(false);
}
/// Window `container` is the server's workstation menu, open here.
pub(super) fn remote_station_open(&self, container: i32) -> bool {
self.station.is_some()
&& self
.remote
.as_ref()
.and_then(|r| r.menu.as_ref())
.is_some_and(|(id, name)| {
*id == container && Self::remote_station_kind(name).is_some()
})
}
/// The server set station slot `internal`: the client menu's
/// `Slot.set` runs its container's `setChanged`, so the loom lists the
/// patterns its inputs allow and the stonecutter the recipes of its input.
pub(super) fn remote_station_slot_changed(&mut self, internal: usize) {
if !self.station.as_ref().is_some_and(|s| {
matches!(
s.kind,
Kind::Loom
| Kind::Stonecutter
| Kind::Grindstone
| Kind::Anvil
| Kind::Smithing
| Kind::Cartography
)
}) {
return;
}
self.menu_session(|menu, env, to_menu| {
let i = to_menu(internal)?;
let stack = menu.slot(i).cloned();
menu.set_slot(env, i, stack);
Some(true)
});
// AnvilScreen.slotChanged: the box shows the new input's name, which
// its responder sends.
self.remote_anvil_rename();
}
/// `AbstractContainerMenu.setData` from the server.
pub(super) fn remote_station_data(&mut self, id: usize, value: i16) {
let Some(s) = self.station.as_mut() else {
return;
};
match (s.kind, id) {
// LoomMenu.selectedBannerPatternIndex.
(Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(),
// StonecutterMenu.selectedRecipeIndex.
(Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(),
// AnvilMenu.cost.
(Kind::Anvil, 0) => s.anvil.cost = i32::from(value),
// EnchantmentMenu: costs, the seed (the screen's glyph names),
// the clues' enchantments and levels.
(Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value),
(Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value),
(Kind::Enchanting, 4..7) => {
let name = self.remote.as_ref().and_then(|r| {
r.registries
.name("minecraft:enchantment", i32::from(value))
.map(std::sync::Arc::<str>::from)
});
let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l);
s.offers.clues[id - 4] = name.map(|n| (n, level));
}
(Kind::Enchanting, 7..10) => {
if let Some((_, level)) = s.offers.clues[id - 7].as_mut() {
*level = value.max(0) as u32;
}
}
// BeaconMenu: the levels, then the powers (BeaconScreen's
// dataChanged shows the menu's).
(Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)),
(Kind::Beacon, 1 | 2) => {
let effect = self.remote_effect_id(i32::from(value) - 1);
let index =
effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e));
if let Some(s) = self.station.as_mut() {
s.beacon[id - 1] = index;
}
}
_ => {}
}
}
/// `AnvilScreen.onNameChanged` on a server: the rename box's text (blank
/// when it is the input's own name) goes to the server when the menu's
/// `setItemName` takes it.
pub(super) fn remote_anvil_rename(&mut self) {
if self.remote.is_none() {
return;
}
let Some(s) = self
.station
.as_ref()
.filter(|s| s.kind == Kind::Anvil && s.inputs[0].is_some())
else {
return;
};
let name = self.anvil_item_name(s);
if s.anvil_sent.as_deref() == Some(&name) {
return;
}
if let Some(s) = self.station.as_mut() {
s.anvil_sent = Some(name.clone());
}
self.send(S::RenameItem(play::RenameItem { name }));
}
/// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already
/// ran `clickMenuButton` on its own menu.
pub(super) fn remote_station_button(&self, button: i32) {
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref())
&& self.remote_station_open(*container)
{
self.send(S::ContainerButtonClick(play::ContainerButtonClick {
container: *container,
button,
}));
}
}
}
+3 -5
View File
@@ -431,20 +431,18 @@ impl Game<'_> {
self.score.board.players_team(self.acting_player_name())
}
/// The teams of the player and of the mobs on one (empty without teams).
pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams {
pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> {
let board = &self.score.board;
if board.teams.is_empty() {
return Default::default();
}
horizon_client::mobs::Teams {
player: self.player_team().cloned(),
player: self.player_team(),
mobs: self
.persist
.uuids
.iter()
.filter_map(|(id, uuid)| {
Some((*id, board.players_team(&uuid_text(*uuid))?.clone()))
})
.filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?)))
.collect(),
}
}
+6 -1
View File
@@ -71,6 +71,8 @@ pub(super) struct SculkState {
/// The sculk block entities in the order they were added.
index: Index,
pub known: HashSet<(i32, i32)>,
/// The chunk map's membership revision `known` was taken at.
pub known_revision: Option<u64>,
// Keyed by mob ids the server gives out: the fast hasher is safe.
steps: FxHashMap<Who, Steps>,
damaged: FxHashMap<u32, i64>,
@@ -336,7 +338,10 @@ impl Game<'_> {
/// the block writes recorded since the last tick.
pub(super) fn sculk_sync_index(&mut self) {
// Chunks that arrived or left (every half second is plenty).
if self.sculk.ticks.is_multiple_of(10) {
// Nothing to do while no chunk came or went.
let revision = self.world.chunks.membership_revision();
if self.sculk.ticks.is_multiple_of(10) && self.sculk.known_revision != Some(revision) {
self.sculk.known_revision = Some(revision);
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
let arrived: Vec<(i32, i32)> = loaded.difference(&self.sculk.known).copied().collect();
for key in arrived {
@@ -433,6 +433,7 @@ impl Game<'_> {
});
self.level_events.clear();
self.sculk.known = self.world.chunks.keys().copied().collect();
self.sculk.known_revision = Some(self.world.chunks.membership_revision());
self.sculk_sync_index();
let mut names: HashMap<u32, String> = HashMap::new();
let mut sources: Vec<u32> = Vec::new();
@@ -665,7 +666,7 @@ impl Game<'_> {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.damage(amount, horizon_client::mobs::Damage::player(at));
}
self.last_hurt_by_player.insert(id);
self.last_hurt_by_player.insert(id, self.lan_acting);
}
"set" => {
let n = |i: usize| words[i].parse::<i32>().unwrap_or(0);
@@ -37,11 +37,8 @@ impl ShaderPacks {
}
}
/// `shaderpacks/` beside `options.txt`.
pub(super) fn dir() -> PathBuf {
std::env::current_dir()
.unwrap_or_default()
.join(shader_pack::DIR)
shader_pack::folder()
}
impl Game<'_> {
@@ -77,6 +74,7 @@ impl Game<'_> {
return self.shader_pack_error(&id, &e.to_string());
}
self.shader_packs.pack = pack;
self.ui.options.shader_pack_error = None;
}
/// Give the loaded pack to the renderer (also after it is rebuilt).
pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> {
@@ -105,6 +103,11 @@ impl Game<'_> {
}
fn shader_pack_error(&mut self, id: &str, error: &str) {
log::warn!("Horizon: shader pack {id}: {error}");
// The Shader Packs page says why on the pack's row: the first line,
// since translator errors go on with a drawn source excerpt.
let first = error.lines().map(str::trim).find(|l| !l.is_empty());
self.ui.options.shader_pack_error =
Some((id.to_owned(), first.unwrap_or(error).to_owned()));
self.system_message(Text::literal(format!("Shader pack {id}: {error}")));
}
}
@@ -373,6 +373,11 @@ impl Loading {
let _ = std::fs::create_dir_all(&dir);
packs::open_folder(&dir);
}
Event::OpenShaderPackFolder => {
let dir = horizon_client::shader_pack::folder();
let _ = std::fs::create_dir_all(&dir);
packs::open_folder(&dir);
}
Event::ButtonClick => {}
}
}
@@ -10,6 +10,7 @@ pub(super) const HELP: &[&str] = &[
"use X Y Z open the block's menu as if right-clicked",
"click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)",
"click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner",
"book [next|back|take|done] the open book or lectern: its page, or press one of its buttons",
"type TEXT | type-back type into the anvil name box / delete one character",
"enchant ID LEVEL enchant the held item (books store the enchantment)",
"potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)",
@@ -136,6 +137,7 @@ impl Game<'_> {
self.apply_equipment();
ok()
}
"book" => Ok(Some(self.book_control(words.get(1).copied())?)),
"potion" => {
let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?));
let rest = self.give(stack);
+173 -401
View File
@@ -13,7 +13,6 @@ use horizon_client::{
stations::{self, AnvilResult, EnchantOffers},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::sync::Arc;
/// Slot ids of the open station: inputs from 600, the result at 650.
pub(super) const INPUT: usize = 600;
@@ -36,7 +35,7 @@ pub(super) enum Kind {
Loom,
}
impl Kind {
fn from_block(name: &str) -> Option<Self> {
pub(super) fn from_block(name: &str) -> Option<Self> {
Some(match name {
"minecraft:enchanting_table" => Self::Enchanting,
"minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => {
@@ -51,7 +50,7 @@ impl Kind {
_ => return None,
})
}
fn inputs(self) -> usize {
pub(super) fn inputs(self) -> usize {
match self {
Self::Smithing | Self::Loom => 3,
Self::Stonecutter | Self::Beacon => 1,
@@ -71,7 +70,7 @@ impl Kind {
Self::Loom => "gui/container/loom",
}
}
fn title_key(self) -> &'static str {
pub(super) fn title_key(self) -> &'static str {
match self {
Self::Enchanting => "container.enchant",
Self::Anvil => "container.repair",
@@ -108,6 +107,10 @@ impl Kind {
};
table[i.min(table.len() - 1)]
}
/// Whether the menu has a result slot after its inputs.
pub(super) fn has_result(self) -> bool {
self.result_pos().is_some()
}
fn result_pos(self) -> Option<(f32, f32)> {
match self {
Self::Enchanting => None,
@@ -128,18 +131,20 @@ pub(super) struct Station {
pub(super) pos: [i32; 3],
pub(super) inputs: Vec<Option<ItemStack>>,
pub(super) result: Option<ItemStack>,
offers: EnchantOffers,
pub(super) offers: EnchantOffers,
bookcases: i32,
anvil: AnvilResult,
pub(super) anvil: AnvilResult,
/// Anvil rename box text.
pub(super) name: String,
/// Stonecutter: recipe indices for the input, selection and first shown index.
recipes: Vec<usize>,
selected: Option<usize>,
/// Stonecutter: the menu's recipe list (horizon_client::menu), its
/// `selectedRecipeIndex` and the screen's first shown index.
pub(super) stone: horizon_client::menu::Stonecutter,
pub(super) selected: Option<usize>,
start: usize,
input_item: Option<Arc<str>>,
/// Anvil: the input the rename box was last filled from.
anvil_last: Option<ItemStack>,
/// Anvil on a server: the name last sent (the client menu's `itemName`).
pub(super) anvil_sent: Option<String>,
/// When the screen opened: the rename box has the focus from then.
opened: std::time::Instant,
pub(super) last_sound: u64,
@@ -147,6 +152,8 @@ pub(super) struct Station {
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
/// Beacon menu: the selected primary and secondary power (EFFECTS index).
pub(super) beacon: [Option<usize>; 2],
/// A server's beacon menu: the pyramid's levels (its data slot 0).
pub(super) beacon_levels: Option<i32>,
/// The loom's patterns, selection and scroller (game/loom.rs).
pub(super) loom: super::loom::LoomState,
}
@@ -161,21 +168,29 @@ impl Station {
bookcases: 0,
anvil: AnvilResult::default(),
name: String::new(),
recipes: Vec::new(),
stone: Default::default(),
selected: None,
start: 0,
input_item: None,
anvil_last: None,
anvil_sent: None,
opened: std::time::Instant::now(),
last_sound: 0,
merchant: None,
beacon: [None; 2],
beacon_levels: None,
loom: Default::default(),
}
}
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
Self::new(kind, pos)
}
/// `StonecutterScreen.containerChanged`: without recipes to show, the
/// list scrolls back to the top.
pub(super) fn stonecutter_changed(&mut self) {
if self.inputs[0].is_none() || self.stone.recipes.is_empty() {
self.start = 0;
}
}
}
/// The 108x19 enchantment button `i` (relative to the GUI origin).
@@ -323,6 +338,10 @@ impl Game<'_> {
let Some(mut station) = self.station.take() else {
return;
};
if self.remote.is_some() && station.kind != Kind::Merchant {
// A server's workstation: its removed() gives the inputs back.
return;
}
if let Some(m) = station.merchant.as_mut() {
self.merchant_closed(m);
}
@@ -375,7 +394,7 @@ impl Game<'_> {
_ => &mut self.scratch_slot,
}
}
fn count_bookshelves(&self, pos: [i32; 3]) -> i32 {
pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 {
let tags = &self.res.items().block_tags;
let is = |p: [i32; 3], tag: &str| {
let name = &self
@@ -399,7 +418,7 @@ impl Game<'_> {
.count() as i32
}
/// The anvil name the menu works with (`AnvilScreen.onNameChanged`).
fn anvil_item_name(&self, s: &Station) -> String {
pub(super) fn anvil_item_name(&self, s: &Station) -> String {
match &s.inputs[0] {
Some(input)
if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) =>
@@ -419,6 +438,16 @@ impl Game<'_> {
let data = self.res.stations();
let items = self.res.items();
match s.kind {
// A server's table: its data slots carry the offers, and its
// client menu only clears them without an enchantable item.
Kind::Enchanting if self.remote.is_some() => {
let enchantable = s.inputs[0].as_ref().is_some_and(|i| {
data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty()
});
if !enchantable {
s.offers = Default::default();
}
}
Kind::Enchanting => {
s.bookcases = self.count_bookshelves(s.pos);
s.offers = stations::enchant_offers(
@@ -465,35 +494,9 @@ impl Game<'_> {
// The menu engine keeps the merchant's result (Game::menu_session).
Kind::Merchant => {}
Kind::Beacon => {}
Kind::Cartography => s.result = self.cartography_result(&s),
// The menu engine keeps the loom's state (Game::menu_session).
Kind::Loom => {}
Kind::Stonecutter => {
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
if item != s.input_item {
s.input_item = item;
s.selected = None;
s.start = 0;
s.recipes = match &s.inputs[0] {
Some(input) => data
.recipes
.stonecutting
.iter()
.enumerate()
.filter(|(_, r)| r.input.test(input))
.map(|(i, _)| i)
.collect(),
None => Vec::new(),
};
}
s.result = match (s.selected, &s.inputs[0]) {
(Some(i), Some(_)) => s
.recipes
.get(i)
.map(|&r| data.recipes.stonecutting[r].result.clone()),
_ => None,
};
}
// The menu engine keeps the cartography table's, the loom's and
// the stonecutter's state (Game::menu_session).
Kind::Cartography | Kind::Loom | Kind::Stonecutter => {}
}
self.station = Some(s);
}
@@ -505,7 +508,6 @@ impl Game<'_> {
}
/// `Slot.mayPlace` and `getMaxStackSize` for station slots.
fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
let data = self.data();
if slot >= super::mount_menu::SADDLE {
return self.mount_slot_rules(slot, stack);
}
@@ -528,24 +530,7 @@ impl Game<'_> {
if slot == RESULT {
return (false, 64);
}
let i = slot - INPUT;
match s.kind {
Kind::Enchanting if i == 0 => (true, 1),
Kind::Beacon => (super::beacon::is_payment(&stack.item), 1),
Kind::Loom => (false, 64),
Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64),
Kind::Cartography => (
matches!(
&*stack.item,
"minecraft:paper" | "minecraft:map" | "minecraft:glass_pane"
),
64,
),
Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64),
Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64),
Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64),
_ => (true, 64),
}
(s.kind != Kind::Loom, 64)
}
/// `AbstractContainerMenu.doClick` PICKUP on a filtered slot.
pub(super) fn click_filtered(&mut self, slot: usize, right: bool) {
@@ -644,112 +629,80 @@ impl Game<'_> {
}
stack.count != start
}
/// The player inventory in menu order: main rows, then the hotbar.
fn player_slots() -> Vec<usize> {
(9..36).chain(0..9).collect()
/// After an anvil or smithing click on the menu engine: the anvil's cost
/// and state back into the station and the rename box following the
/// input (`AnvilScreen.slotChanged`), then the rest of a taken result's
/// `onTake` (the levels, the anvil's wear, the use sound) unless a
/// server does it.
pub(super) fn combiner_session_end(
&mut self,
menu: &horizon_client::menu::Menu,
predicting: bool,
) {
let Some(s) = self.station.as_mut() else {
return;
};
let (pos, kind) = (s.pos, s.kind);
if kind == Kind::Anvil {
s.anvil.cost = menu.data[0];
s.anvil.repair_item_count_cost = menu.anvil.repair_count;
s.anvil.only_renaming = menu.anvil.only_renaming;
s.anvil.result = s.result.clone();
}
self.station_after_input();
if !menu.combined || predicting {
return;
}
if kind == Kind::Smithing {
self.level_event_at(1044, pos, 0);
return;
}
self.give_levels(menu.level_change);
if self.anvil_used(pos, self.creative) {
self.close_station();
self.screen = Screen::Playing;
self.capture(true);
}
}
/// A shift-click: `AbstractContainerMenu.doClick`'s QUICK_MOVE repeats
/// `quickMoveStack` while it moves something and the slot still holds the
/// same item.
fn quick_move(&mut self, slot: usize) {
while let Some(item) = self.slot_mut(slot).as_ref().map(|s| s.item.clone())
&& self.quick_move_once(slot)
&& self.slot_mut(slot).as_ref().is_some_and(|s| s.item == item)
{}
}
/// The station menu's `quickMoveStack` for one slot (`EnchantmentMenu`,
/// `BeaconMenu`, `GrindstoneMenu`, `StonecutterMenu`,
/// `CartographyTableMenu`, and `ItemCombinerMenu` with `SmithingMenu`'s
/// `canMoveIntoInputSlots`); whether the stack's count changed. Each
/// rule that names its target slots moves nowhere else when they are full.
fn quick_move_once(&mut self, slot: usize) -> bool {
let Some(kind) = self.station.as_ref().map(|s| s.kind) else {
return false;
};
let Some(mut stack) = self.slot_mut(slot).take() else {
return false;
};
let start = stack.count;
let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none();
// The other half of the inventory: main rows to the hotbar and back.
let halves: Vec<usize> = if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
};
if slot >= INPUT {
// An input slot: into the inventory, the hotbar's last slot first
// where vanilla moves in reverse.
let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon);
self.move_to(&mut stack, &Self::player_slots(), reverse);
} else {
match kind {
Kind::Enchanting => {
if &*stack.item == "minecraft:lapis_lazuli" {
self.move_to(&mut stack, &[INPUT + 1], true);
} else if empty(self, 0) {
*self.station_slot_mut(INPUT) = Some(ItemStack {
count: 1,
..stack.clone()
});
stack.count -= 1;
}
/// `AnvilMenu.onTake`'s level part: out of creative a 12% chance
/// (`AnvilBlock.damage`) to wear the anvil a stage, or break a damaged one
/// (level event 1029); otherwise level event 1030. True when it broke.
pub(super) fn anvil_used(&mut self, pos: [i32; 3], creative: bool) -> bool {
let state = self.world.block(pos[0], pos[1], pos[2]);
let name = self.res.facts().get(state).name.clone();
let anvil = matches!(
&*name,
"minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil"
);
if !creative && anvil && self.world.random.next_float() < 0.12 {
match &*name {
"minecraft:anvil" => {
let _ = self.set_state_named(pos, "minecraft:chipped_anvil", &["facing"]);
}
Kind::Beacon => {
if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1
{
self.move_to(&mut stack, &[INPUT], false);
} else {
self.move_to(&mut stack, &halves, false);
}
"minecraft:chipped_anvil" => {
let _ = self.set_state_named(pos, "minecraft:damaged_anvil", &["facing"]);
}
Kind::Grindstone => {
if empty(self, 0) || empty(self, 1) {
self.move_to(&mut stack, &[INPUT, INPUT + 1], false);
} else {
self.move_to(&mut stack, &halves, false);
}
_ => {
let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air);
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.level_event_at(1029, pos, 0);
return true;
}
Kind::Stonecutter => {
if self.data().recipes.stonecutter(&stack).is_empty() {
self.move_to(&mut stack, &halves, false);
} else {
self.move_to(&mut stack, &[INPUT], false);
}
}
Kind::Cartography => {
if super::maps::map_id(&stack).is_some() {
self.move_to(&mut stack, &[INPUT], false);
} else if matches!(
&*stack.item,
"minecraft:paper" | "minecraft:map" | "minecraft:glass_pane"
) {
self.move_to(&mut stack, &[INPUT + 1], false);
} else {
self.move_to(&mut stack, &halves, false);
}
}
Kind::Anvil | Kind::Smithing => {
let inputs: Vec<usize> = (0..kind.inputs()).map(|i| INPUT + i).collect();
// ItemCombinerMenu.canMoveIntoInputSlots: always for the
// anvil; the smithing table needs an empty slot whose
// ingredient test takes the stack.
let into_inputs = kind == Kind::Anvil
|| (0..3).any(|i| {
empty(self, i) && self.data().recipes.smithing_accepts(i, &stack)
});
let targets = if into_inputs { &inputs } else { &halves };
self.move_to(&mut stack, targets, false);
}
// Their clicks run on the menu engine.
Kind::Merchant | Kind::Loom => {}
}
}
let moved = stack.count != start;
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
self.level_event_at(1030, pos, 0);
false
}
/// The grindstone result's `onTake` with a level (`amount`: the menu's
/// `getExperienceAmount` sum): the orbs at the block's centre
/// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound
/// for everyone around.
pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) {
let xp = stations::grindstone_xp_roll(amount, &mut self.world.random);
if xp > 0 {
self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp);
}
moved
self.level_event_at(1042, pos, 0);
}
fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) {
let at = [
@@ -788,185 +741,6 @@ impl Game<'_> {
_ => true,
}
}
/// The result slot's `onTake`.
fn take_result(&mut self) {
let Some(mut s) = self.station.take() else {
return;
};
let pos = s.pos;
match s.kind {
Kind::Anvil => {
let cost = s.anvil.cost;
let repair = s.anvil.repair_item_count_cost;
if repair > 0 {
if let Some(a) = s.inputs[1].as_mut()
&& a.count > repair
{
a.count -= repair;
} else {
s.inputs[1] = None;
}
} else if !s.anvil.only_renaming {
s.inputs[1] = None;
}
s.inputs[0] = None;
s.name.clear();
if !self.creative {
self.give_levels(-cost);
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
if !self.creative && self.world.random.next_float() < 0.12 {
// AnvilBlock.damage
let state = self.world.block(pos[0], pos[1], pos[2]);
let name = self.res.facts().get(state).name.clone();
let next = match &*name {
"minecraft:anvil" => Some("minecraft:chipped_anvil"),
"minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"),
_ => None,
};
match next {
Some(next) => {
let _ = self.set_state_named(pos, next, &["facing"]);
self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch);
}
None => {
let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air);
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch);
self.station = Some(s);
self.close_station();
self.screen = Screen::Playing;
self.capture(true);
return;
}
}
} else {
self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch);
}
}
Kind::Grindstone => {
let (a, b) = (s.inputs[0].take(), s.inputs[1].take());
let mut random = LegacyRandom::new(self.world.random.next_long());
let xp = stations::grindstone_experience(
&self.res.stations().enchantments,
&mut random,
a.as_ref(),
b.as_ref(),
);
if xp > 0 {
self.spawn_orbs(
[
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
],
xp,
);
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch);
}
Kind::Smithing => {
for slot in s.inputs.iter_mut() {
if let Some(x) = slot.as_mut() {
x.count -= 1;
if x.count == 0 {
*slot = None;
}
}
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch);
}
Kind::Stonecutter => {
if let Some(x) = s.inputs[0].as_mut() {
x.count -= 1;
if x.count == 0 {
s.inputs[0] = None;
}
}
if s.last_sound != self.ticks {
s.last_sound = self.ticks;
self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0);
}
}
Kind::Merchant => {}
Kind::Beacon => {}
Kind::Cartography => {
for slot in &mut s.inputs {
if let Some(x) = slot.as_mut() {
x.count -= 1;
if x.count == 0 {
*slot = None;
}
}
}
if s.last_sound != self.ticks {
s.last_sound = self.ticks;
self.cartography_taken(pos);
}
}
Kind::Loom => {}
Kind::Enchanting => {}
}
self.station = Some(s);
self.station_changed();
}
fn click_result(&mut self, shift: bool) {
loop {
let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else {
return;
};
if !self.may_take_result() {
return;
}
let result = if self
.station
.as_ref()
.is_some_and(|s| s.kind == Kind::Cartography)
{
self.cartography_post(result)
} else {
result
};
if shift {
let mut stack = result.clone();
let player = Self::player_slots();
// Simulate first so nothing is lost when the inventory is full.
let saved: Vec<Option<ItemStack>> = self.inventory.clone();
self.move_to(&mut stack, &player, true);
if stack.count > 0 {
self.inventory = saved;
return;
}
} else {
match &mut self.carried {
None => self.carried = Some(result.clone()),
Some(c)
if c.same_item_same_components(&result)
&& c.count + result.count
<= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) =>
{
c.count += result.count
}
_ => return,
}
}
if let Some(s) = self.station.as_mut() {
s.result = None;
}
self.take_result();
let again = shift
&& self
.station
.as_ref()
.and_then(|s| s.result.as_ref())
.is_some_and(|r| r.item == result.item);
if !again {
return;
}
}
}
/// `EnchantmentMenu.clickMenuButton`.
fn click_enchant(&mut self, button: usize) {
let Some(s) = self.station.as_ref() else {
@@ -987,6 +761,11 @@ impl Game<'_> {
{
return;
}
if self.remote.is_some() {
// EnchantmentScreen.mouseClicked: the client menu took it, the server enchants.
self.remote_station_button(button as i32);
return;
}
let Some(enchanted) = stations::apply_enchantment(
&self.res.stations().enchantments,
self.res.items(),
@@ -1036,7 +815,7 @@ impl Game<'_> {
})
.collect(),
Kind::Stonecutter if s.inputs[0].is_some() => (s.start
..(s.start + 12).min(s.recipes.len()))
..(s.start + 12).min(s.stone.recipes.len()))
.map(|index| {
let p = index - s.start;
[
@@ -1089,64 +868,21 @@ impl Game<'_> {
}
}
}
if kind == Kind::Stonecutter
&& let Some(s) = self.station.as_ref()
&& s.inputs[0].is_some()
{
for index in s.start..(s.start + 12).min(s.recipes.len()) {
let p = index - s.start;
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
if inside(local, x, y, 16.0, 18.0) {
if s.selected != Some(index) {
if let Some(st) = self.station.as_mut() {
st.selected = Some(index);
}
self.audio.play(
"minecraft:ui.stonecutter.select_recipe",
None,
1.0,
1.0,
);
self.station_changed();
}
return true;
}
}
if kind == Kind::Stonecutter && self.stonecutter_click(local) {
return true;
}
}
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return true;
};
if self
.station
.as_ref()
.is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant))
{
// LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu
// clicks run on the verified menu engine.
let input = if shift {
horizon_client::menu::Input::QuickMove
} else {
horizon_client::menu::Input::Pickup
};
self.menu_click(Some(slot), i32::from(right), input);
return true;
}
if slot == RESULT {
self.click_result(shift);
return true;
}
if shift {
self.quick_move(slot);
} else if slot >= INPUT {
self.click_filtered(slot, right);
// Every station's clicks (and the brewing stand's) run on the
// verified menu engine.
let input = if shift {
horizon_client::menu::Input::QuickMove
} else {
return false;
}
if let Some(key) = self.container {
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
}
self.station_after_input();
horizon_client::menu::Input::Pickup
};
self.menu_click(Some(slot), i32::from(right), input);
true
}
/// Recompute after slot changes; the anvil box follows its input item.
@@ -1164,16 +900,49 @@ impl Game<'_> {
}
self.station_changed();
}
/// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton`
/// with the cell's index (an empty cell's too), and the select sound when
/// the menu took it.
fn stonecutter_click(&mut self, local: (f32, f32)) -> bool {
let Some(start) = self
.station
.as_ref()
.filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty())
.map(|s| s.start)
else {
return false;
};
for index in start..start + 12 {
let p = index - start;
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
if !inside(local, x, y, 16.0, 18.0) {
continue;
}
let mut taken = false;
let flag = &mut taken;
self.menu_session(|menu, env, _| {
*flag = menu.button(env, index as i32);
Some(*flag)
});
if taken {
self.audio
.play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0);
self.remote_station_button(index as i32);
return true;
}
}
false
}
pub(super) fn station_scroll(&mut self, d: f32) {
self.merchant_scroll(d);
self.loom_scroll(d);
let Some(s) = self.station.as_mut() else {
return;
};
if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 {
if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 {
return;
}
let rows = s.recipes.len().div_ceil(4) - 3;
let rows = s.stone.recipes.len().div_ceil(4) - 3;
let first_row = (s.start / 4) as i32 - d.signum() as i32;
s.start = first_row.clamp(0, rows as i32) as usize * 4;
}
@@ -1207,6 +976,7 @@ impl Game<'_> {
}
}
self.station_changed();
self.remote_anvil_rename();
}
/// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the
/// recipe book's search box.
@@ -1227,6 +997,7 @@ impl Game<'_> {
ANVIL_NAME_CHARS,
) {
self.station_changed();
self.remote_anvil_rename();
}
}
@@ -1740,9 +1511,9 @@ impl Game<'_> {
}
Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {}
Kind::Stonecutter => {
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
let active = display && s.recipes.len() > 12;
let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1);
let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty();
let active = display && s.stone.recipes.len() > 12;
let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1);
let offs = if active {
(s.start / 4) as f32 / rows as f32
} else {
@@ -1763,13 +1534,14 @@ impl Game<'_> {
let (start, selected) = (s.start, s.selected);
// graphics.item: the icon only, without the count.
let shown: Vec<(usize, ItemStack)> = (start
..(start + 12).min(s.recipes.len()))
..(start + 12).min(s.stone.recipes.len()))
.map(|i| {
(
i,
ItemStack {
count: 1,
..self.res.stations().recipes.stonecutting[s.recipes[i]]
..self.res.stations().recipes.stonecutting
[s.stone.recipes[i]]
.result
.clone()
},
@@ -2082,7 +1854,7 @@ impl Game<'_> {
"bookcases": s.bookcases,
"anvil_cost": s.anvil.cost,
"result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)),
"recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
"recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
"selected": s.selected,
})
}
+35
View File
@@ -122,6 +122,38 @@ impl Game<'_> {
let sky = self.world.light(x, y + 1, z) >> 4 == 15;
water || (self.world.weather.raining && sky)
}
/// The living entities a spinning player can touch this tick, for
/// `LivingEntity.checkAutoSpinAttack` (none when not spinning).
pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> {
let Some(p) = self
.player
.as_ref()
.filter(|p| p.auto_spin_attack_ticks > 0)
else {
return Vec::new();
};
// A spin moves a few blocks a tick at most.
let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0));
self.mobs
.iter()
.filter(|m| m.alive() && m.bounds().intersects(near))
.map(|m| (m.id, m.bounds()))
.collect()
}
/// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack`
/// with the spin's damage; once the spin is over its damage is cleared.
pub(super) fn end_spin_attack(&mut self, hit: Option<u32>) {
if let Some(id) = hit
&& let Some(index) = self.mobs.iter().position(|m| m.id == id)
{
self.attack_mob(index);
}
if let Some(p) = self.player.as_mut()
&& p.auto_spin_attack_ticks <= 0
{
p.auto_spin_attack_dmg = 0.0;
}
}
/// `TridentItem.releaseUsing`.
pub(super) fn release_trident(&mut self, ticks: u32) {
if ticks < 10 {
@@ -152,6 +184,9 @@ impl Game<'_> {
p.velocity.y + d[1] * f64::from(strength),
p.velocity.z + d[2] * f64::from(strength),
);
// Player.startAutoSpinAttack(20, 8, stack).
p.auto_spin_attack_ticks = 20;
p.auto_spin_attack_dmg = 8.0;
if p.ground.on_ground {
p.position.y += 1.2;
}
+1 -1
View File
@@ -131,7 +131,7 @@ impl Game<'_> {
m.damage(1.0, source);
}
if p.owner == Some(Who::Player) {
self.last_hurt_by_player.insert(id);
self.last_hurt_by_player.insert(id, self.lan_acting);
}
}
}
+114 -16
View File
@@ -34,6 +34,7 @@ fn entity_shader() -> String {
mod entity_batch;
use entity_batch::EntityBatch;
pub use entity_batch::WATER_MASK_OVERLAY;
/// Window.getAppropriateLineWidth, in framebuffer pixels.
pub fn outline_width(width: u32) -> f32 {
@@ -106,12 +107,16 @@ struct Globals {
fog_ends: [f32; 4],
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
end_portal_sprites: [[f32; 4]; 2],
/// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused.
/// x: vanilla's `GameTime` uniform; y: nether cardinal lighting; z: how many
/// `dynamic_lights` are set; w unused.
time: [f32; 4],
/// Atlas rect of the current destroy stage (entity.wgsl).
/// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same,
/// and each crack carries its own stage's origin).
crumbling_sprite: [f32; 4],
/// Framebuffer size, selection stroke width, perspective layering scale.
outline_params: [f32; 4],
/// Horizon Extras' dynamic lights: camera-relative position and level (`dynamic_light`).
dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX],
}
pub type SectionKey = (i32, i32, i32);
struct SectionGpu {
@@ -184,6 +189,8 @@ pub struct Frame<'a> {
pub nether_lighting: bool,
/// Camera-relative entity geometry textured from the shared atlas.
pub entities: &'a [Vertex],
/// Horizon Extras' dynamic lights, nearest first (`dynamic_light::select`); empty when off.
pub dynamic_lights: &'a [[f32; 4]],
/// Cloud mesh inputs; geometry and GPU storage are retained by the renderer.
pub clouds: Option<crate::clouds::Input<'a>>,
/// Additive translucent geometry after the entities (lightning, dragon rays).
@@ -212,7 +219,8 @@ pub struct Frame<'a> {
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png
/// (`rendertype_end_portal`'s Sampler0 and Sampler1).
pub end_portal_sprites: [[f32; 4]; 2],
/// Current destroy-stage sprite: projected UVs repeat inside this atlas rect.
/// A destroy-stage sprite: projected UVs repeat inside a rect of this size, from the
/// origin each crack vertex carries (`breaking::stage_light`).
pub crumbling_sprite: [f32; 4],
pub ticks: u64,
/// The darkness effect on the lightmap: the brightness it takes off the
@@ -317,6 +325,8 @@ pub struct Renderer {
crosshair_globals: wgpu::Buffer,
entity_pipeline: wgpu::RenderPipeline,
crumbling_pipeline: wgpu::RenderPipeline,
/// `RenderPipelines.WATER_MASK`: depth writes only, no colour.
water_mask_pipeline: wgpu::RenderPipeline,
cloud_pipeline: wgpu::RenderPipeline,
cloud_mesh: crate::clouds::Mesh,
cloud_buffer: wgpu::Buffer,
@@ -1539,7 +1549,16 @@ impl Renderer {
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &entity_attributes,
})];
let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| {
#[allow(clippy::too_many_arguments)]
let entity_pipeline_with = |label,
cull_mode,
depth_write,
compare,
bias,
blend,
clouds,
fragment: &str,
write_mask| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(if clouds {
@@ -1567,18 +1586,43 @@ impl Renderer {
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &entity_shader,
entry_point: Some("fs_entity"),
entry_point: Some(fragment),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
write_mask,
})],
}),
multiview_mask: None,
cache: None,
})
};
let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| {
entity_pipeline_with(
label,
cull_mode,
depth_write,
compare,
bias,
blend,
clouds,
"fs_entity",
wgpu::ColorWrites::ALL,
)
};
// RenderPipelines.WATER_MASK: the boat's water patch writes depth only.
let water_mask_pipeline = entity_pipeline_with(
"Water mask",
None,
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
false,
"fs_water_mask",
wgpu::ColorWrites::empty(),
);
let crumbling_pipeline = entity_pipeline(
"Breaking cracks",
Some(wgpu::Face::Back),
@@ -2058,6 +2102,7 @@ impl Renderer {
crosshair_globals,
entity_pipeline,
crumbling_pipeline,
water_mask_pipeline,
cloud_pipeline,
cloud_mesh: Default::default(),
cloud_buffer,
@@ -2868,10 +2913,17 @@ impl Renderer {
time: [
frame.shader_game_time,
f32::from(frame.nether_lighting),
0.0,
frame.dynamic_lights.len().min(crate::dynamic_light::MAX) as f32,
0.0,
],
outline_params: outline_params(self.config.width, self.config.height),
dynamic_lights: {
let mut lights = [[0.0; 4]; crate::dynamic_light::MAX];
for (to, from) in lights.iter_mut().zip(frame.dynamic_lights) {
*to = *from;
}
lights
},
};
self.uploads
.buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals));
@@ -3183,14 +3235,19 @@ impl Renderer {
self.uploads
.buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines));
}
let [entity_quads, crumbling_quads, translucent_crumbling_quads] =
self.entity_batch.update(
frame.entities,
frame.additive,
frame.hand,
frame.see_through,
);
let world_quads = entity_quads + crumbling_quads + translucent_crumbling_quads;
let [
entity_quads,
crumbling_quads,
translucent_crumbling_quads,
water_mask_quads,
] = self.entity_batch.update(
frame.entities,
frame.additive,
frame.hand,
frame.see_through,
);
let world_quads =
entity_quads + crumbling_quads + translucent_crumbling_quads + water_mask_quads;
let cloud_quads = if let Some(input) = &frame.clouds {
let (rebuilt, uniform) =
crate::spans::time("clouds", || self.cloud_mesh.prepare(input));
@@ -3552,6 +3609,19 @@ impl Renderer {
pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
// BoatRenderer's water patch (RenderTypes.waterMask): depth only,
// before translucent terrain, so no water shows inside the boat.
if water_mask_quads > 0 {
pass.set_pipeline(&self.water_mask_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..water_mask_quads * 6,
((entity_quads + crumbling_quads + translucent_crumbling_quads) * 4) as i32,
0..1,
);
pass.set_bind_group(0, &self.group, &[]);
}
if additive_quads > 0 {
pass.set_pipeline(&self.additive_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
@@ -4097,6 +4167,34 @@ mod tests {
);
assert_eq!(surface_format(&[Rgba16Float], Bgra8UnormSrgb), Rgba16Float);
}
/// A Wayland surface on a compositor with colour management, as wgpu lists it (Mesa 26.2
/// ANV on an Intel HD 620 under weston 16): wide formats first. The pre-#1075 choice,
/// the first non-sRGB format, took `Rgba16Float` and the window looked washed out, as if
/// under a white overlay (#1007); XWayland lists no such format, which is why it looked fine.
#[test]
fn a_colour_managed_wayland_surface_still_gets_8_bit() {
use super::surface_format;
use wgpu::TextureFormat::*;
let wayland = [
Rgba16Float,
Rgba16Unorm,
Rgb10a2Unorm,
Bgra8UnormSrgb,
Bgra8Unorm,
Rgba8UnormSrgb,
Rgba8Unorm,
];
assert_eq!(surface_format(&wayland, Bgra8UnormSrgb), Bgra8Unorm);
// Without Bgra8: Rgba8, still not a 16- or 10-bit format.
let without_bgra = [
Rgba16Float,
Rgba16Unorm,
Rgb10a2Unorm,
Rgba8UnormSrgb,
Rgba8Unorm,
];
assert_eq!(surface_format(&without_bgra, Rgba8UnormSrgb), Rgba8Unorm);
}
#[test]
fn special_material_batches_preserve_quad_order_and_offsets() {
let quad = |layer, id| {
@@ -4116,7 +4214,7 @@ mod tests {
let mut batch = super::EntityBatch::default();
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8));
let vertices = &batch.combined;
assert_eq!(counts, [4, 1, 1]);
assert_eq!(counts, [4, 1, 1, 0]);
assert_eq!(
vertices
.as_chunks::<4>()
+16 -7
View File
@@ -1,12 +1,19 @@
//! Stable entity material grouping with renderer-owned, reusable CPU scratch.
use super::Vertex;
/// Entity materials by a quad's overlay (`Vertex::layer`), in draw order:
/// ordinary entities, breaking cracks (11), translucent breaking cracks (12)
/// and the boat water mask (13, `RenderPipelines.WATER_MASK`).
const MATERIALS: usize = 4;
/// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`).
pub const WATER_MASK_OVERLAY: u32 = 13;
#[derive(Default)]
pub(super) struct EntityBatch {
// Quad indices avoid copying vertices twice while grouping materials.
// Keep initialized high-water storage; local counts delimit active entries.
// Each bucket can hold all quads, removing per-quad Vec growth checks.
buckets: [Vec<usize>; 3],
buckets: [Vec<usize>; MATERIALS],
pub(super) combined: Vec<Vertex>,
}
@@ -17,18 +24,19 @@ impl EntityBatch {
additive: &[Vertex],
hand: &[Vertex],
see_through: &[Vertex],
) -> [u32; 3] {
) -> [u32; MATERIALS] {
let quads = entities.as_chunks::<4>().0;
for bucket in &mut self.buckets {
if bucket.len() < quads.len() {
bucket.resize(quads.len(), 0);
}
}
let mut counts = [0usize; 3];
let mut counts = [0usize; MATERIALS];
for (index, quad) in quads.iter().enumerate() {
let material = match quad[0].layer {
11 => 1,
12 => 2,
WATER_MASK_OVERLAY => 3,
_ => 0,
};
self.buckets[material][counts[material]] = index;
@@ -77,14 +85,15 @@ mod tests {
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
) -> (Vec<Vertex>, [u32; 3]) {
) -> (Vec<Vertex>, [u32; MATERIALS]) {
let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len());
let mut counts = [0; 3];
for (i, layer) in [0, 11, 12].into_iter().enumerate() {
let mut counts = [0; MATERIALS];
for (i, layer) in [0, 11, 12, 13].into_iter().enumerate() {
for quad in entities.as_chunks::<4>().0 {
let material = match quad[0].layer {
11 => 11,
12 => 12,
13 => 13,
_ => 0,
};
if material == layer {
@@ -104,7 +113,7 @@ mod tests {
pos: [index as f32, 2.0, 3.0],
uv: [index as f32, 5.0],
layer: if mixed {
[7, 11, 12, 4, 0][index / 4 % 5]
[7, 11, 12, 4, 13, 0][index / 4 % 6]
} else {
0
},
+30 -17
View File
@@ -237,7 +237,7 @@ pub fn rows(level: Level) -> Vec<Row> {
h(
H::ShaderPack,
High,
"Redraws the world with a pack from shaderpacks/. Off is vanilla.",
"Redraws the world with a pack from the shaderpacks folder. Off is vanilla.",
),
Row::Header("Preferences"),
v(Opt::ViewBobbing, None, "Sways the view while walking."),
@@ -422,17 +422,6 @@ impl H {
H::Antialiasing => g.fxaa = !g.fxaa,
H::BatteryMode => g.battery = !g.battery,
H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back),
H::ShaderPack => {
// Off, then every pack in shaderpacks/ by folder name.
let dir = std::env::current_dir()
.unwrap_or_default()
.join(crate::shader_pack::DIR);
let mut all = vec![String::new()];
all.extend(crate::shader_pack::list(&dir).into_iter().map(|(id, _)| id));
let i = all.iter().position(|x| *x == g.shader_pack).unwrap_or(0);
let n = all.len();
g.shader_pack = all[if back { (i + n - 1) % n } else { (i + 1) % n }].clone();
}
H::Pacing => {
g.pacing = match g.pacing {
Pacing::Efficient => Pacing::Precise,
@@ -559,6 +548,8 @@ pub enum Action {
Changed,
OpenAdvanced,
OpenSimple,
/// The Shader Pack row: the Shader Packs page (where packs are picked).
OpenShaderPacks,
Done,
}
@@ -784,6 +775,9 @@ impl GraphicsUi {
}
return match wd.target {
Target::Button(action) => vec![Action::ButtonClick, action],
Target::Item(Item::Horizon(H::ShaderPack)) => {
vec![Action::ButtonClick, Action::OpenShaderPacks]
}
Target::Item(item) => {
if item.slider(s).is_some() {
self.dragging = Some(item);
@@ -1003,11 +997,30 @@ mod tests {
);
s.horizon.shader_pack = "horizon-sample".into();
assert_eq!(row.label(&s).plain(), "Shader Pack: horizon-sample");
// Picking a pack keeps the preset.
Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]);
let preset = s.horizon.preset;
row.cycle(&mut s, false, [854, 480]);
assert_eq!(s.horizon.preset, preset);
// The row opens the Shader Packs page, where packs are picked.
let mut ui = GraphicsUi::default();
let find = |ui: &mut GraphicsUi| {
let (widgets, ..) = ui.layout(Level::Advanced, 854.0, 480.0);
widgets
.into_iter()
.find(|w| matches!(w.target, Target::Item(i) if i == row))
.unwrap()
};
ui.scroll = find(&mut ui).y - GraphicsUi::bounds(480.0).0 - 4.0;
let w = find(&mut ui);
assert_eq!(
ui.click(
Level::Advanced,
&mut s,
(w.x + 1.0, w.y + 1.0),
(854.0, 480.0),
[854, 480],
false,
false
),
[Action::ButtonClick, Action::OpenShaderPacks]
);
assert_eq!(s.horizon.shader_pack, "horizon-sample");
}
#[test]
+65
View File
@@ -231,6 +231,10 @@ impl PlayerHealth {
.get(self.ids.absorption)
.expect("validated absorption field")
}
/// The game time the damage clock has counted.
pub fn game_time(&self) -> i64 {
self.game_time
}
pub fn dead_or_dying(&self) -> bool {
self.health() <= 0.0 || self.dead
}
@@ -274,6 +278,11 @@ impl PlayerMotion {
.damage
.source::<()>(source, None, None, None)
.ok_or("unknown resident damage source")?;
let armor = self.attribute("minecraft:armor").unwrap_or(0.0) as f32;
let toughness = self.attribute("minecraft:armor_toughness").unwrap_or(0.0) as f32;
let before = self.health.health() + self.health.absorption();
let fire_ticks = self.fire_ticks;
let source_name = source.definition().name.clone();
let totem_ready = self.health.totem_ready;
let invulnerable = self.invulnerable;
let h = &mut self.health;
@@ -312,6 +321,23 @@ impl PlayerMotion {
if outcome.hurt {
h.hurt_animation_time = h.hurt.hurt_time;
}
let after = h.health() + h.absorption();
if self.hurt_log.len() >= HURT_LOG {
self.hurt_log.remove(0);
}
self.hurt_log.push(HurtRecord {
game_time: h.game_time,
source: source_name,
amount,
blocked: outcome.blocked,
taken: before - after,
hurt: outcome.hurt,
armor,
toughness,
health: after,
fire_ticks,
knockback: None,
});
Ok(outcome)
}
pub fn set_health(&mut self, value: f32, absorption: bool) -> Result<()> {
@@ -363,6 +389,45 @@ pub struct Blocking {
/// Angle between the head's view and the source position (pi without one).
pub angle: f64,
}
/// How many hurts `PlayerMotion::hurt_log` keeps.
const HURT_LOG: usize = 64;
/// One hurt as it was taken: what came in, what a raised blocking item
/// stopped, the armour it met and what health it left.
#[derive(Clone, Debug, PartialEq)]
pub struct HurtRecord {
pub game_time: i64,
/// The damage type.
pub source: String,
/// The damage before blocking, armour and effects.
pub amount: f32,
pub blocked: f32,
/// Health and absorption lost.
pub taken: f32,
pub hurt: bool,
/// `minecraft:armor` and `minecraft:armor_toughness` when it came.
pub armor: f32,
pub toughness: f32,
pub health: f32,
/// The fire ticks before the hurt.
pub fire_ticks: i32,
/// The push the hurt gave, if the caller applied one.
pub knockback: Option<[f64; 3]>,
}
/// One melee attack on a mob: the damage after the attack strength, the
/// strength (`getAttackStrengthScale`), and the health it took.
#[derive(Clone, Debug, PartialEq)]
pub struct AttackRecord {
pub game_time: i64,
pub target: String,
/// The mob's entity id, and whether the blow killed it.
pub id: u32,
pub killed: bool,
pub amount: f32,
pub scale: f32,
pub crit: bool,
pub landed: bool,
pub dealt: f32,
}
/// The outcome of a hurt with a raised blocking item.
#[derive(Clone, Copy, Debug, Default)]
pub struct BlockOutcome {
+74
View File
@@ -0,0 +1,74 @@
//! The anonymous "I'm playing" ping (`horizon_telemetry::live`, docs/telemetry.md) behind the
//! launcher's "N playing now". While the game runs, a thread of its own sends a random session
//! ID made here and kept only in memory, the version, the platform and whether a LAN or
//! play-with-friends world is open, every minute and at once when that last one changes.
//! It sends nothing when there is no server (`HORIZON_TELEMETRY_URL`, none by default) or
//! with `HORIZON_NO_HEARTBEAT=1` (automated runs).
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::Thread;
use std::time::Duration;
use horizon_telemetry::live::{self, Ping};
/// A world is open to LAN or to friends.
static LAN: AtomicBool = AtomicBool::new(false);
static PINGER: OnceLock<Thread> = OnceLock::new();
/// After a failure the next ping waits longer, doubling up to this.
const MAX_WAIT: Duration = Duration::from_secs(600);
/// Starts the pings, once. Call when the game itself starts (not a dedicated server, not a
/// benchmark or an automated run).
pub fn start() {
if PINGER.get().is_some() || std::env::var_os("HORIZON_NO_HEARTBEAT").is_some() {
return;
}
let Some(endpoint) = horizon_telemetry::endpoint() else {
return;
};
let spawned = std::thread::Builder::new()
.name("Heartbeat".into())
.spawn(move || run(&endpoint));
match spawned {
Ok(handle) => {
let _ = PINGER.set(handle.thread().clone());
}
Err(e) => log::warn!("Horizon: no live count ping: {e}"),
}
}
/// Whether a world is open to LAN or friends; a change is sent at once.
pub fn set_lan(open: bool) {
if LAN.swap(open, Ordering::Relaxed) != open
&& let Some(pinger) = PINGER.get()
{
pinger.unpark();
}
}
fn run(endpoint: &str) {
let session = live::session_id();
let version = crate::telemetry::version();
let mut wait = live::INTERVAL;
let mut failed = false;
loop {
let ping = Ping::new(&session, &version, LAN.load(Ordering::Relaxed));
match live::send(endpoint, &ping) {
Ok(()) => {
wait = live::INTERVAL;
failed = false;
}
Err(e) => {
// Said once, not every minute the server is away.
if !failed {
log::info!("Horizon: the live count ping failed ({e}); trying again later");
}
failed = true;
wait = (wait * 2).min(MAX_WAIT);
}
}
// Woken early by `set_lan`; a spurious wake only sends one ping more.
std::thread::park_timeout(wait);
}
}
+2 -6
View File
@@ -594,12 +594,8 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
),
));
}
if let Some(mode) = d.map_post_processing {
entries.push((
"minecraft:map_post_processing",
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
));
}
// minecraft:map_post_processing is transient: ItemStack.CODEC never
// saves it (only the network carries it).
if !d.charged.is_empty() {
entries.push((
"minecraft:charged_projectiles",
+19
View File
@@ -1434,6 +1434,13 @@ impl LootContext<'_> {
.count() as u32;
}
}
// SetPotionFunction (the barter's fire resistance potions).
"minecraft:set_potion" => {
if let Some(id) = f["id"].as_str() {
*stack = std::mem::replace(stack, ItemStack::new("minecraft:air", 0))
.with_potion(id);
}
}
"minecraft:limit_count" => {
let limit = &f["limit"];
if let Some(min) = limit["min"].as_i64() {
@@ -1631,6 +1638,18 @@ mod tests {
);
}
#[test]
fn set_potion_gives_the_potion_its_contents() {
let items = Items::for_tests(HashMap::new());
let props = BTreeMap::new();
let table = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item","name":"minecraft:splash_potion",
"modifier":{"type":"minecraft:set_potion","id":"minecraft:fire_resistance"}}]}]});
let drops = ctx(&items, None, &props, "").evaluate(&table, &mut LegacyRandom::new(1));
assert_eq!(drops.len(), 1);
assert_eq!(&*drops[0].item, "minecraft:splash_potion");
assert_eq!(drops[0].potion(), Some("minecraft:fire_resistance"));
}
#[test]
fn always_edible_and_consume_effects_loaded() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+39
View File
@@ -179,4 +179,43 @@ mod tests {
);
assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple");
}
/// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the
/// game loads them, with their default options: the compatibility table
/// of docs/shader-packs.md. Skipped when the variable isn't set.
#[test]
fn real_packs_load() {
let Some(dir) = std::env::var_os("HORIZON_TEST_SHADERPACKS") else {
return;
};
let mut entries: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| is_java_pack(p))
.collect();
entries.sort();
let mut failures = Vec::new();
for path in entries {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") {
Ok(pack) => {
let folders: Vec<String> = pack
.folders
.iter()
.map(|f| {
let n = f.passes.len() + usize::from(f.final_pass.is_some());
format!("{} {n} passes", f.folder)
})
.collect();
println!("{name}: loads ({})", folders.join(", "));
}
Err(e) => {
println!("{name}: {e}");
failures.push(name);
}
}
}
assert!(failures.is_empty(), "{failures:?}");
}
}
+1 -1
View File
@@ -778,7 +778,7 @@ fn play(c: Connection, shared: &Arc<Shared>, parts: Parts, address: std::net::So
std::thread::Builder::new()
.name(format!("horizon-lan-out-{conn_id}"))
.spawn(move || {
// A dedicated server's tick comes first (horizon_threads).
// Ticks and frames come first (horizon_threads).
horizon_threads::behind_server();
write_loop(writer, rx, alive, latency, pending)
})
+16 -4
View File
@@ -455,18 +455,30 @@ impl Hub {
let Slots::Block(pos) = m.slots else {
return;
};
// AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess.
// AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess,
// CrafterBlockEntity.containerData.
let data = match world.block_entities.get(&pos) {
Some(BlockEntity::Furnace(f)) => [
Some(BlockEntity::Furnace(f)) => vec![
f.lit_remaining,
f.lit_total,
f.cooking_timer,
f.cooking_total,
],
Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel],
Some(BlockEntity::Brewing(b)) => {
vec![b.brew_time, b.fuel, b.total_brew_time, b.total_fuel]
}
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
Some(BlockEntity::Crafter(c)) => c
.disabled
.iter()
.chain([&c.triggered])
.map(|&d| i32::from(d))
.collect(),
_ => return,
}
.map(|v| v as i16);
.into_iter()
.map(|v| v as i16)
.collect::<Vec<i16>>();
m.sent_data.resize(data.len(), i16::MIN);
let window = m.window;
let changed: Vec<(usize, i16)> = data
+95 -2
View File
@@ -34,7 +34,7 @@ pub fn changed_attributes(
}
/// What the game says about one entity this tick.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EntityState {
pub id: i32,
pub uuid: u128,
@@ -61,6 +61,72 @@ pub struct EntityState {
pub precise: bool,
}
impl EntityState {
/// The entity `id` of type `kind` as a fresh state has it: at the origin,
/// at rest, with no data, equipment or attributes. Keeps the allocations
/// of the strings and vectors it held.
pub fn reset(&mut self, id: i32, uuid: u128, kind: &str) {
self.id = id;
self.uuid = uuid;
self.kind.clear();
self.kind.push_str(kind);
self.position = [0.0; 3];
(self.yaw, self.pitch, self.head_yaw) = (0.0, 0.0, 0.0);
self.on_ground = false;
self.velocity = [0.0; 3];
self.data = 0;
self.meta.clear();
self.equipment.clear();
self.attributes.clear();
self.precise = false;
}
}
/// The states a level describes its entities with, kept from tick to tick:
/// each tick's are written over the last tick's in place, so the strings and
/// vectors in them are reused instead of being made and freed again for every
/// entity on every tick.
#[derive(Default)]
pub struct States {
list: Vec<EntityState>,
len: usize,
}
impl States {
/// Start a new tick's states.
pub fn clear(&mut self) {
self.len = 0;
}
/// The next entity's state, reset (`EntityState::reset`).
pub fn add(&mut self, id: i32, uuid: u128, kind: &str) -> &mut EntityState {
if self.len == self.list.len() {
self.list.push(EntityState::default());
}
let e = &mut self.list[self.len];
self.len += 1;
e.reset(id, uuid, kind);
e
}
pub fn push(&mut self, e: EntityState) {
match self.list.get_mut(self.len) {
Some(slot) => *slot = e,
None => self.list.push(e),
}
self.len += 1;
}
pub fn as_slice(&self) -> &[EntityState] {
&self.list[..self.len]
}
}
impl Extend<EntityState> for States {
fn extend<I: IntoIterator<Item = EntityState>>(&mut self, states: I) {
for e in states {
self.push(e);
}
}
}
/// `AbstractArrow`: every update sends its position and rotation.
fn is_arrow(kind: &str) -> bool {
matches!(
@@ -393,11 +459,13 @@ impl ServerEntity {
.collect();
// A value back at its default is left out of the state, but the
// clients still hold the old one: Entity's shared flags and pose go
// back to 0 (a player standing up again, a mob no longer on fire).
// back to 0 (a player standing up again, a mob no longer on fire),
// a sleeper's bed to none.
for (index, kind, _) in &self.meta {
let default = match (*index, *kind) {
(0, serializer::BYTE) => Value::Byte(0),
(6, serializer::POSE) => Value::Id(0),
(14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None),
_ => continue,
};
if !e.meta.iter().any(|m| m.0 == *index) {
@@ -790,6 +858,31 @@ mod tests {
}
}
#[test]
fn states_are_written_over_last_ticks_in_place() {
let mut states = States::default();
let e = states.add(1, 1, "minecraft:zombie");
e.position = [1.0, 2.0, 3.0];
e.meta.push((9, serializer::FLOAT, Value::Float(20.0)));
e.equipment.push((0, None));
let (kind, meta) = (e.kind.as_ptr(), e.meta.as_ptr());
states.push(state(2.0));
states.clear();
let e = states.add(3, 3, "minecraft:husk");
// Nothing of the last tick's state is left, but its allocations are.
let fresh = EntityState {
id: 3,
uuid: 3,
kind: "minecraft:husk".into(),
..EntityState::default()
};
assert_eq!(*e, fresh);
assert_eq!((e.kind.as_ptr(), e.meta.as_ptr()), (kind, meta));
assert_eq!(states.as_slice(), std::slice::from_ref(&fresh));
states.extend([state(5.0), state(6.0)]);
assert_eq!(states.as_slice(), [fresh, state(5.0), state(6.0)]);
}
/// The entity as added this tick, then its updates (one a tick).
fn added(e: &EntityState) -> ServerEntity {
ServerEntity::new(e, Some(100), &Riding::default())
+48
View File
@@ -122,6 +122,13 @@ pub struct Guest {
pub tracker: Tracker,
// Player state the gameplay code reads and writes.
pub motion: Option<Box<PlayerMotion>>,
/// The hurt and attack logs of the body it had before it respawned,
/// until the new body takes them over (the control socket's `hurtlog`
/// reads across a death).
pub logs_kept: Option<(
Vec<crate::health::HurtRecord>,
Vec<crate::health::AttackRecord>,
)>,
/// The 36 inventory slots (hotbar first), armor (head..feet) and off hand.
pub inventory: Vec<Option<ItemStack>>,
pub armor: [Option<ItemStack>; 4],
@@ -140,6 +147,8 @@ pub struct Guest {
pub xp_level: i32,
pub xp_progress: f32,
pub xp_total: i32,
/// `Player.enchantmentSeed` (the enchanting table's offers).
pub xp_seed: i32,
/// Active status effects (`LivingEntity.activeEffects`).
pub effects: crate::effects::PlayerEffects,
/// What the client was told of each effect: id, amplifier, flags, and
@@ -251,6 +260,7 @@ impl Guest {
batch_quota: 0.0,
tracker: Tracker::default(),
motion: None,
logs_kept: None,
inventory: vec![None; 36],
armor: [None, None, None, None],
offhand: None,
@@ -265,6 +275,7 @@ impl Guest {
xp_level: 0,
xp_progress: 0.0,
xp_total: 0,
xp_seed: 0,
effects: Default::default(),
sent_effects: Vec::new(),
menu_sent: vec![None; 46],
@@ -410,6 +421,43 @@ pub fn stack_to_network(
horizon_protocol::item::Component::Int(id),
));
}
if d.repair_cost > 0 {
stack.added.push((
horizon_protocol::item::component::REPAIR_COST,
horizon_protocol::item::Component::Int(d.repair_cost as i32),
));
}
if let Some(mode) = d.map_post_processing {
stack.added.push((
horizon_protocol::item::component::MAP_POST_PROCESSING,
horizon_protocol::item::Component::Int(i32::from(mode)),
));
}
// The books a lectern shows and a guest reads.
if !d.writable_pages.is_empty() {
stack.added.push((
horizon_protocol::item::component::WRITABLE_BOOK_CONTENT,
horizon_protocol::item::Component::WritableBook(d.writable_pages.clone()),
));
}
if let Some(w) = &d.written {
stack.added.push((
horizon_protocol::item::component::WRITTEN_BOOK_CONTENT,
horizon_protocol::item::Component::WrittenBook(
horizon_protocol::item::WrittenBook {
title: w.title.clone(),
author: w.author.clone(),
generation: i32::from(w.generation),
pages: w
.pages
.iter()
.map(|p| horizon_protocol::text::literal(p))
.collect(),
resolved: true,
},
),
));
}
}
if let Some(name) = s.custom_name() {
stack.added.push((
+127 -15
View File
@@ -85,6 +85,8 @@ pub struct HostState {
pub attributes: Vec<play::AttributeSnapshot>,
/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` (the item in use).
pub living_flags: i8,
/// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`).
pub bed: Option<[i32; 3]>,
}
/// Everything the hub needs from the game for one tick.
@@ -240,6 +242,30 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
/// The view's queue around a new centre: the queued chunks still tracked, then
/// the tracked ones neither sent nor queued, closest first (a stable sort, so
/// equally close chunks keep their order).
fn requeue(
queue: &mut Vec<(i32, i32)>,
sent: &crate::fast_hash::FxHashSet<(i32, i32)>,
(cx, cz): (i32, i32),
r: i32,
) {
queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
// A walking player changes chunk every few ticks with hundreds of chunks
// queued: a set, not a scan of the queue for each of the view's chunks.
let mut queued: crate::fast_hash::FxHashSet<(i32, i32)> = queue.iter().copied().collect();
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && queued.insert(key) {
queue.push(key);
}
}
}
queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
}
/// What a level's players were last told of its clock and weather.
#[derive(Clone, Copy)]
struct LevelSync {
@@ -309,6 +335,11 @@ impl Hub {
self.sync.id(registry, name)
}
/// The name of a network id in a built-in registry.
pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> {
self.sync.builtin.get(registry)?.name(id)
}
pub fn item_id(&mut self, item: &Arc<str>) -> i32 {
if let Some(id) = self.item_ids.get(item) {
return *id;
@@ -1288,20 +1319,7 @@ impl Hub {
g.sent_chunks.remove(&(x, z));
g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] }));
}
g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if tracked(cx, cz, r, key.0, key.1)
&& !g.sent_chunks.contains(&key)
&& !g.chunk_queue.contains(&key)
{
g.chunk_queue.push(key);
}
}
}
g.chunk_queue
.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
requeue(&mut g.chunk_queue, &g.sent_chunks, (cx, cz), r);
}
/// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first,
@@ -1467,6 +1485,7 @@ impl Hub {
on_ground: bool,
flags: (bool, bool, bool, bool),
living_flags: i8,
bed: Option<[i32; 3]>,
skin: u8,
health: f32,
equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>,
@@ -1502,6 +1521,11 @@ impl Hub {
// Always there: the trackers send the entries that changed, and an
// item no longer in use is a change back to 0.
meta.push((8, serializer::BYTE, Value::Byte(living_flags)));
// LivingEntity.SLEEPING_POS: the others draw the player lying in it,
// a player paired later too.
if let Some(bed) = bed.filter(|_| sleeping) {
meta.push((14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(Some(bed))));
}
if (health - 1.0).abs() > f32::EPSILON && health != 20.0 {
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
@@ -1565,8 +1589,9 @@ impl Hub {
h.position,
(h.yaw, h.pitch, h.head_yaw),
h.on_ground,
(h.sneaking, h.sprinting, false, false),
(h.sneaking, h.sprinting, false, h.bed.is_some()),
h.living_flags,
h.bed,
0x7F,
h.health,
equipment,
@@ -1598,6 +1623,7 @@ impl Hub {
g.on_ground,
(g.sneaking, g.sprinting, g.fall_flying, g.sleeping),
g.living_flags,
g.bed,
g.info.model_customisation,
g.health,
equipment,
@@ -1862,6 +1888,7 @@ impl Hub {
// (handlePlayerKnownMovement), PlayerInput once loaded.
let acted = match &packet {
S::AcceptTeleportation(_)
| S::PlayerAbilities(_)
| S::MovePlayerStatus(_)
| S::MovePlayerRot(_)
| S::PlayerLoaded(_)
@@ -1899,6 +1926,11 @@ impl Hub {
self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events);
}
}
// handlePlayerAbilities: the client flies only if it may.
S::PlayerAbilities(p) => {
let g = &mut self.guests[i];
g.flying = p.flags & 2 != 0 && (g.creative() || g.spectator());
}
S::MovePlayerPos(p) => {
self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events);
}
@@ -2173,6 +2205,13 @@ impl Hub {
return;
};
g.game_mode = mode;
// GameType.updatePlayerAbilities: a spectator flies, survival and
// adventure don't, creative keeps what it had.
if g.spectator() {
g.flying = true;
} else if !g.creative() {
g.flying = false;
}
let uuid = g.uuid;
g.send(&C::GameEvent(play::GameEvent {
event: game_event::CHANGE_GAME_MODE,
@@ -2457,3 +2496,76 @@ fn ticking_state(rate: f32, frozen: bool) -> C {
w.bool(frozen);
raw(ids::TICKING_STATE, w.data)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fast_hash::FxHashSet;
/// `requeue` as it was, scanning the queue for each chunk of the view.
fn requeue_scan(
queue: &mut Vec<(i32, i32)>,
sent: &FxHashSet<(i32, i32)>,
(cx, cz): (i32, i32),
r: i32,
) {
queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && !queue.contains(&key)
{
queue.push(key);
}
}
}
queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
}
/// A player walking a loop, sending a few chunks a tick: the queue
/// after every move is the one the scan built.
#[test]
fn requeue_matches_the_scan() {
for r in [2, 5, 10, 12, 32] {
let (mut a, mut b) = (Vec::new(), Vec::new());
let mut sent = FxHashSet::default();
for step in 0..60i32 {
let center = ((step % 17) - 8, (step * 3 % 11) - 5);
requeue(&mut a, &sent, center, r);
requeue_scan(&mut b, &sent, center, r);
assert_eq!(a, b, "radius {r}, step {step}");
for key in a.drain(..a.len().min(7)) {
sent.insert(key);
}
b.drain(..b.len().min(7));
sent.retain(|&(x, z)| tracked(center.0, center.1, r, x, z));
}
}
}
/// cargo test --release -p horizon-client --lib lan::hub::tests::requeue_cost -- --ignored --nocapture
#[test]
#[ignore]
fn requeue_cost() {
for r in [10, 16, 32] {
for (name, f) in [
("scan", requeue_scan as fn(&mut _, &_, _, _)),
("set", requeue as fn(&mut _, &_, _, _)),
] {
let sent = FxHashSet::default();
let mut queue = Vec::new();
let start = std::time::Instant::now();
let moves = 200;
for step in 0..moves {
// Nothing sent yet (an explorer waiting on generation).
f(&mut queue, &sent, (step, 0), r);
}
let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(moves);
println!(
"view {r}: {name} {per:.1} us per chunk crossed, {} queued",
queue.len()
);
}
}
}
}
@@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.xp_level = level.xp_level;
guest.xp_progress = level.xp_progress;
guest.xp_total = level.xp_total;
guest.xp_seed = level.xp_seed;
guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects);
guest.game_mode = level.mode();
guest.flying = level.flying;
@@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.xp_level = guest.xp_level;
level.xp_progress = guest.xp_progress;
level.xp_total = guest.xp_total;
level.xp_seed = guest.xp_seed;
level.active_effects = guest.effects.saved();
level.game_mode = guest.game_mode;
level.creative = guest.game_mode == 1;
+50 -1
View File
@@ -153,6 +153,9 @@ pub struct Waypoints {
/// One tick's players, and the packets for their connections.
struct Tick<'a> {
players: HashMap<u128, &'a Player>,
/// The connections of the players in other levels: one who just left this level is
/// still told of the waypoints it loses (`removePlayer` disconnects them).
away: &'a [(u128, u32)],
view: HashMap<u128, ([i32; 2], i32)>,
/// Players a respawn replaced this tick: a new ServerPlayer, on its first tick.
fresh: &'a [u128],
@@ -169,7 +172,17 @@ impl<'a> Tick<'a> {
icon: &Icon,
target: WaypointTarget,
) {
let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else {
let Some(conn) = self
.players
.get(&receiver)
.and_then(|p| p.conn)
.or_else(|| {
self.away
.iter()
.find(|(uuid, _)| *uuid == receiver)
.map(|&(_, conn)| conn)
})
else {
return;
};
self.out
@@ -449,9 +462,22 @@ impl Waypoints {
players: &[Player],
respawned: &[u128],
locator_bar: bool,
) -> Vec<(u32, C)> {
self.tick_level(players, &[], respawned, locator_bar)
}
/// [`Self::tick`] for one level of several: `away` are the connections of the players
/// in the other levels, for the untracks owed to one who has just left this one.
pub fn tick_level(
&mut self,
players: &[Player],
away: &[(u128, u32)],
respawned: &[u128],
locator_bar: bool,
) -> Vec<(u32, C)> {
let mut t = Tick {
players: players.iter().map(|p| (p.uuid, p)).collect(),
away,
view: HashMap::default(),
fresh: respawned,
enabled: locator_bar,
@@ -632,6 +658,29 @@ mod tests {
assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]);
}
#[test]
fn a_player_leaving_the_level_loses_its_waypoints() {
let (a, b) = (
player(1, 10, [0.5, 64.0, 0.5]),
player(2, 20, [4.5, 64.0, 0.5]),
);
let mut w = Waypoints::default();
w.tick(&[a.clone(), b.clone()], &[], true);
let mut moved = b.clone();
moved.position = [5.5, 64.0, 0.5];
w.tick(&[a.clone(), moved], &[], true);
// B goes to another level: A loses B, and B (reached through `away`) loses A.
let out = w.tick_level(std::slice::from_ref(&a), &[(2, 20)], &[], true);
assert_eq!(
to(&out, 10),
vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)]
);
assert_eq!(
to(&out, 20),
vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)]
);
}
#[test]
fn team_colours() {
assert_eq!(team_rgb("red"), Some(0xFF5555));
+2
View File
@@ -51,6 +51,7 @@ pub mod datapack;
pub mod debug_chart;
pub mod debug_keys;
pub mod debug_overlay;
pub mod dynamic_light;
pub mod effects;
pub mod enchant;
pub mod end_crystal;
@@ -79,6 +80,7 @@ pub mod graphics;
pub mod graphics_style;
pub mod graphics_ui;
pub mod health;
pub mod heartbeat;
pub mod hotbar;
pub mod hud;
pub mod hud_layout;

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