Merge pull request #787 from ludovic111/bm2/combined

🤖 Agent: merged the six LAN guest fixes for #696 (#722–#727), combined on main and checked locally (clippy, tests, parity lan/dedicated_server/mob_ai, lan_e2e clicks/sleep/push/eat/xp).
This commit is contained in:
Ludovic Marie
2026-10-18 02:09:22 +02:00
committed by GitHub
22 changed files with 1071 additions and 114 deletions
@@ -999,6 +999,7 @@ fn main() -> horizon_client::Result<()> {
hero: false,
uuid: PLAYER_UUID,
allies: Default::default(),
remote: false,
}
});
let mut scratch = LegacyRandom::new(0);
+2
View File
@@ -179,6 +179,8 @@ impl ItemEntity {
/// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks.
#[derive(Clone, Debug)]
pub struct ExperienceOrb {
/// The entity id servers track it by.
pub id: u32,
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
+2
View File
@@ -943,6 +943,7 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
};
let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
let orb = ExperienceOrb {
id: 0,
position,
previous: position,
velocity: motion(tag),
@@ -1587,6 +1588,7 @@ mod tests {
#[test]
fn orbs_expand_their_count() {
let o = ExperienceOrb {
id: 0,
position: Vec3::new(1.0, 2.0, 3.0),
previous: Vec3::ZERO,
velocity: Vec3::ZERO,
+110 -51
View File
@@ -4599,6 +4599,10 @@ impl Game<'_> {
/// Several clicks on one menu instance (a quick craft drag is three).
fn menu_ops(&mut self, ops: &[(Option<usize>, i32, horizon_client::menu::Input)]) -> bool {
use horizon_client::menu::Input;
if self.remote.is_some() && self.screen == Screen::Inventory {
// On a server the clicks are the server's: predicted and sent.
return self.remote_menu_ops(ops);
}
if let [(Some(slot), button, input)] = ops {
self.crafter_slot_clicked(*slot, *button, *input);
}
@@ -4773,7 +4777,7 @@ impl Game<'_> {
plain: false,
};
(kind, map)
} else if self.station.is_none() && !self.mount_active() && self.remote.is_none() {
} else if self.station.is_none() && !self.mount_active() {
let table = self.craft_size == 3;
let map = Map {
container: 0,
@@ -4886,7 +4890,12 @@ impl Game<'_> {
Some(false) => return true,
Some(true) => {}
}
self.register_exploration_maps(made);
// On a server the clicks only predict: the server drops, crafts and
// makes maps itself.
let predicting = self.remote.is_some();
if !predicting {
self.register_exploration_maps(made);
}
if let Some(s) = menu.merchant.take() {
self.merchant_sync_out(s);
}
@@ -4904,10 +4913,12 @@ impl Game<'_> {
if !offhand_mapped {
self.offhand = menu.player_item(40).cloned();
}
for stack in dropped {
self.player_drop(stack);
if !predicting {
for stack in dropped {
self.player_drop(stack);
}
self.award_crafted(&crafted);
}
self.award_crafted(&crafted);
if kind == Kind::Loom {
if let Some(s) = self.station.as_mut() {
s.loom.selected = usize::try_from(menu.data[0]).ok();
@@ -5039,9 +5050,13 @@ impl Game<'_> {
return;
}
if let Some(moved) = self.last_quick_moved.clone() {
self.menu_session(|menu, env, to_menu| {
Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok())
});
if self.remote.is_some() {
self.remote_quick_move_all(slot, &moved);
} else {
self.menu_session(|menu, env, to_menu| {
Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok())
});
}
}
self.last_inv_click = None;
self.inv_clicks.skip_release();
@@ -7431,7 +7446,9 @@ impl Game<'_> {
let mut r = dispenser::entity_random();
let _yaw = r.next_float();
let p = Vec3::new(at[0], at[1], at[2]);
self.next_entity += 1;
self.orbs.push(ExperienceOrb {
id: self.next_entity,
position: p,
previous: p,
velocity: Vec3::new(
@@ -7495,13 +7512,29 @@ impl Game<'_> {
.player
.as_ref()
.filter(|p| !p.health.dead_or_dying() && !spectator);
let target = player.map(|p| {
[
p.position.x,
p.position.y + f64::from(p.dimensions.eye_height) / 2.0,
p.position.z,
]
});
// ExperienceOrb.followNearbyPlayer: each orb goes for the nearest
// living player within 8 blocks, the host's own or a guest.
let mut followed: Vec<([f64; 3], [f64; 3])> = player
.map(|p| {
let feet = [p.position.x, p.position.y, p.position.z];
let eye = f64::from(p.dimensions.eye_height);
(feet, [feet[0], feet[1] + eye / 2.0, feet[2]])
})
.into_iter()
.collect();
if let Some(host) = self.lan.as_ref() {
followed.extend(
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && g.health > 0.0)
.filter(|g| !g.spectator())
.map(|g| {
let p = g.position;
(p, [p[0], p[1] + g.eye_height() / 2.0, p[2]])
}),
);
}
let bounds = player.map(|p| {
let w = f64::from(p.dimensions.width) / 2.0;
(
@@ -7514,7 +7547,19 @@ impl Game<'_> {
)
});
let mut orbs = std::mem::take(&mut self.orbs);
orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target));
orbs.retain_mut(|o| {
let distance = |feet: &[f64; 3]| -> f64 {
(feet[0] - o.position.x).powi(2)
+ (feet[1] - o.position.y).powi(2)
+ (feet[2] - o.position.z).powi(2)
};
let target = followed
.iter()
.filter(|(feet, _)| distance(feet) < 64.0)
.min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0)))
.map(|(_, target)| *target);
o.tick(&self.world, &self.res.facts, self.collision, target)
});
let mut gained = 0;
let mut taken = Vec::new();
if let Some((min, max)) = bounds {
@@ -7548,19 +7593,25 @@ impl Game<'_> {
(self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9;
self.audio
.play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch);
if self.experience.give(gained as i32)
&& self.experience.level % 5 == 0
&& self.ticks > self.last_level_up + 100
{
self.last_level_up = self.ticks;
let volume = if self.experience.level > 30 {
1.0
} else {
self.experience.level as f32 / 30.0
};
self.audio
.play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0);
}
self.give_orb_points(gained);
}
}
/// `Player.giveExperiencePoints`, and `giveExperienceLevels`' level-up
/// sound every fifth level (at most every 100 ticks).
pub(super) fn give_orb_points(&mut self, gained: u32) {
let at = self.eye_position();
if self.experience.give(gained as i32)
&& self.experience.level % 5 == 0
&& self.ticks > self.last_level_up + 100
{
self.last_level_up = self.ticks;
let volume = if self.experience.level > 30 {
1.0
} else {
self.experience.level as f32 / 30.0
};
self.audio
.play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0);
}
}
/// BowItem.releaseUsing: power from charge time, arrows at power * 3.
@@ -8122,40 +8173,48 @@ impl Game<'_> {
self.stats.reset("custom", "minecraft:time_since_rest");
}
fn wake_up(&mut self) {
if self.remote.is_some() {
// InBedChatScreen.sendWakeUp: the server wakes the player.
self.remote_stop_sleeping();
return;
}
self.sleeping = None;
self.sleep_timer = 100;
}
fn tick_sleep(&mut self) {
self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
let Some(head) = self.sleeping else {
return;
};
if self.keys.contains(&KeyCode::ShiftLeft)
|| self
.player
.as_ref()
.is_none_or(|p| p.health.dead_or_dying())
{
self.wake_up();
return;
if let Some(head) = self.sleeping {
if self.keys.contains(&KeyCode::ShiftLeft)
|| self
.player
.as_ref()
.is_none_or(|p| p.health.dead_or_dying())
{
self.wake_up();
return;
}
if let Some(p) = self.player.as_mut() {
p.position = Vec3::new(
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
);
p.velocity = Vec3::ZERO;
}
}
if let Some(p) = self.player.as_mut() {
p.position = Vec3::new(
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
);
p.velocity = Vec3::ZERO;
}
// ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather.
if self.sleep_timer >= 100 {
// ServerLevel.tick: once enough of the players have slept 100 ticks,
// skip to morning, clear the weather and wake everyone.
if self.enough_slept() {
let t = self.world.day_time;
self.world.day_time = t + 24000 - t.rem_euclid(24000);
self.world.weather.raining = false;
self.world.weather.thundering = false;
self.world.weather.rain_time = 0;
self.world.weather.thunder_time = 0;
self.wake_up();
if self.sleeping.is_some() {
self.wake_up();
}
self.wake_guests();
}
}
fn creative_origin(batch: &HudBatch) -> (f32, f32) {
+4
View File
@@ -466,6 +466,10 @@ impl Game<'_> {
}),
"dimension": self.dim.id(),
"gamemode": format!("{:?}", self.mode).to_lowercase(),
// The bed (its head) the player sleeps in.
"sleeping": self.sleeping,
// The item in use: its slot and for how many ticks.
"using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })),
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
"weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering },
"paused": self.pause,
@@ -1453,7 +1453,9 @@ impl Game<'_> {
return Err(err("commands.summon.failed", &[]));
}
"experience_orb" => {
self.next_entity += 1;
self.orbs.push(horizon_client::entities::ExperienceOrb {
id: self.next_entity,
position: Vec3::new(pos[0], pos[1], pos[2]),
previous: Vec3::new(pos[0], pos[1], pos[2]),
velocity: Vec3::new(0.0, 0.0, 0.0),
@@ -196,6 +196,7 @@ impl Game<'_> {
hero: self.potions.effects.get("hero_of_the_village").is_some(),
uuid: self.level.player_uuid.unwrap_or_default(),
allies: std::sync::Arc::new(self.player_allies()),
remote: false,
})
}
/// Biome facts at a position for finalizeSpawn and variant rules.
+19 -1
View File
@@ -370,6 +370,7 @@ impl Game<'_> {
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"sleeping": g.bed,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
@@ -714,7 +715,7 @@ impl Game<'_> {
/// Mobs and items as the entities guests track.
fn lan_entities(&self, hub: &mut Hub) -> Vec<EntityState> {
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len());
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len());
for m in self.mobs.iter().filter(|m| !m.removed) {
let kind = m.kind.id.as_str();
let meta = mob_meta(m, hub);
@@ -752,6 +753,23 @@ impl Game<'_> {
equipment: Vec::new(),
});
}
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(),
});
}
out
}
+182 -2
View File
@@ -18,7 +18,7 @@ use horizon_client::{
},
motion::{MotionEvent, MotionWorld, PlayerMotion},
};
use horizon_core::geometry::Vec3;
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_protocol::{
packets::play::{self, Clientbound as C, Serverbound as S},
text::literal,
@@ -56,6 +56,8 @@ pub(super) struct GuestPlay {
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
xp_delay: u32,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -172,6 +174,16 @@ impl Game<'_> {
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
let host_station = self.station.take();
// The guest's bed, sleep counter and respawn point; the host's
// respawn point, anchor and action bar stay theirs.
let sleeping = std::mem::replace(&mut self.sleeping, g.bed);
let sleep_timer = std::mem::replace(&mut self.sleep_timer, g.sleep_timer);
let spawn = std::mem::replace(
&mut self.spawn,
g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])),
);
let respawn = (self.respawn_config.take(), self.level.spawn);
let message = self.message.take();
// The guest's own ender inventory; one the host has open goes back
// into the host's while the guest acts.
let host_ender = self.ender_open;
@@ -203,6 +215,12 @@ impl Game<'_> {
let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3;
self.craft_grid = craft_grid;
let opened_station = std::mem::replace(&mut self.station, host_station);
let bed = std::mem::replace(&mut self.sleeping, sleeping);
let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer);
let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]);
(self.respawn_config, self.level.spawn) = respawn;
// ServerPlayer.displayClientMessage(_, true): the guest's action bar.
let guest_message = std::mem::replace(&mut self.message, message);
self.riding = riding;
self.left = left;
self.right = right;
@@ -220,6 +238,15 @@ impl Game<'_> {
self.mount_menu = host_mount_menu;
self.keys = host_keys;
let g = &mut host.hub.guests[i];
let fell_asleep = bed.is_some() && g.bed.is_none();
(g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn);
g.sleeping = g.bed.is_some();
if let Some((text, _)) = guest_message {
g.send(&C::SystemChat(play::SystemChat {
content: literal(&text),
overlay: true,
}));
}
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
@@ -269,6 +296,19 @@ impl Game<'_> {
}
}
let g = &mut host.hub.guests[i];
if let Some(head) = g.bed.filter(|_| fell_asleep) {
// LivingEntity.startSleeping: in the bed, still.
let at = [
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
];
g.position = at;
if let Some(m) = g.motion.as_mut() {
m.position = Vec3::new(at[0], at[1], at[2]);
m.velocity = Vec3::ZERO;
}
}
if new_mode != g.game_mode {
let conn = g.conn;
host.hub.set_game_mode(conn, new_mode);
@@ -966,10 +1006,19 @@ impl Game<'_> {
}
fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) {
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
// The guest's own bed, else the world spawn: never the host's bed.
let world = self
.level
.world_spawn
.map(|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]);
let spawn = host.hub.guests[i]
.spawn
.or(world)
.or(self.spawn.map(|s| [s.x, s.y, s.z]))
.unwrap_or([0.5, 80.0, 0.5]);
if !host.hub.guests[i].dead {
return;
}
@@ -1041,6 +1090,7 @@ impl Game<'_> {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
continue;
};
self.guest_sleep_tick(host, gi);
if host.hub.guests[gi].dead || self.on_server_trip(conn) {
continue;
}
@@ -1083,6 +1133,7 @@ impl Game<'_> {
host.hub.flush_progress(conn);
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
self.guest_orbs(host, gi);
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
@@ -1106,6 +1157,62 @@ impl Game<'_> {
}
}
/// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a
/// sleeper who died or whose bed is gone.
fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) {
let g = &mut host.hub.guests[gi];
g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some());
if let Some(head) = g.bed {
let block = self.world.block(head[0], head[1], head[2]);
let bed = self.res.facts.get(block).name.ends_with("_bed");
if g.dead || g.health <= 0.0 || !bed {
host.hub.wake(gi);
}
}
}
/// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the
/// host's player and the guests: of the players not in spectator mode,
/// players_sleeping_percentage of them (at least one) are in bed, and as
/// many have slept 100 ticks.
pub(super) fn enough_slept(&self) -> bool {
let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64);
let mut count = |in_bed: bool, timer: u32| {
active += 1;
if in_bed {
sleeping += 1;
if timer >= 100 {
deep += 1;
}
}
};
if self.player.is_some() && !self.spectator() {
count(self.sleeping.is_some(), self.sleep_timer);
}
if let Some(host) = self.lan.as_ref() {
for g in host
.hub
.guests
.iter()
.filter(|g| g.placed && !g.spectator())
{
count(g.bed.is_some(), g.sleep_timer);
}
}
let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0));
let needed = ((active * percent + 99) / 100).max(1);
sleeping >= needed && deep >= needed
}
/// `ServerLevel.wakeUpAllPlayers` for the guests.
pub(super) fn wake_guests(&mut self) {
if let Some(host) = self.lan.as_mut() {
for i in 0..host.hub.guests.len() {
host.hub.wake(i);
}
}
}
/// `PlayerList.broadcastSystemMessage` of the advancements guests made
/// (their own actions, commands and ticks).
fn announce_guest_advancements(&mut self, host: &mut LanHost) {
@@ -1384,6 +1491,79 @@ impl Game<'_> {
}
}
/// `Player.tick`'s takeXpDelay and `Player.aiStep`'s touch of the
/// experience orbs in the guest's box grown by 1, 0.5, 1: one of them at
/// random, at most every 2 ticks (`ExperienceOrb.playerTouch`), repairs
/// with Mending and gives the rest as points. Everyone near hears it.
fn guest_orbs(&mut self, host: &mut LanHost, gi: usize) {
let g = &host.hub.guests[gi];
// Player's standing and crouching boxes: 1.8 and 1.5 high.
let height = if g.sneaking { 1.5 } else { 1.8 };
let (conn, id, at) = (g.conn, g.entity_id, g.position);
let unable = g.spectator() || g.dead || g.health <= 0.0;
let play = host.play.entry(conn).or_default();
if play.xp_delay > 0 {
play.xp_delay -= 1;
}
if unable || play.xp_delay > 0 {
return;
}
let (min, max) = (
[at[0] - 1.3, at[1] - 0.5, at[2] - 1.3],
[at[0] + 1.3, at[1] + height + 0.5, at[2] + 1.3],
);
let touching: Vec<usize> = self
.orbs
.iter()
.enumerate()
.filter(|(_, o)| {
o.position.x + 0.25 > min[0]
&& o.position.x - 0.25 < max[0]
&& o.position.y + 0.5 > min[1]
&& o.position.y < max[1]
&& o.position.z + 0.25 > min[2]
&& o.position.z - 0.25 < max[2]
})
.map(|(i, _)| i)
.collect();
if touching.is_empty() {
return;
}
// Util.getRandom(orbs, random).
let pick = self
.world
.random
.next_int_bound(touching.len() as i32)
.unwrap_or(0) as usize;
let orb = self.orbs.remove(touching[pick]);
play.xp_delay = 2;
host.hub.take_item(orb.id as i32, id, 1, at);
// ClientPacketListener.handleTakeItemEntity's sound, at the orb.
let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9;
let p = orb.position;
self.audio.play(
"minecraft:entity.experience_orb.pickup",
Some([p.x, p.y, p.z]),
0.1,
pitch,
);
let value = orb.value;
if let Some(target) = super::pickups::guest_target(host, id as u32) {
use super::pickups::{Collector, Taken};
self.add_pickup_toward(
Taken::Orb(Box::new(orb)),
Collector::Guest(id as u32),
target,
);
}
self.as_guest(host, conn, |game| {
let rest = game.mending(value);
if rest > 0 {
game.give_orb_points(rest);
}
});
}
/// The host's own `ItemPickupParticle` toward the guest's model.
fn guest_pickup(
&mut self,
@@ -107,6 +107,7 @@ impl Game<'_> {
v.velocity = Vec3::new(moved[0], moved[1], moved[2]);
v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid);
v.allies = Default::default();
v.remote = true;
views.push((conn, v));
}
}
@@ -274,6 +275,7 @@ mod tests {
hero: false,
uuid: [0; 4],
allies: Default::default(),
remote: false,
}
}
+7 -1
View File
@@ -176,7 +176,13 @@ impl Game<'_> {
self.dropped.push(e);
}
}
"minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)),
"minecraft:experience_orb" => {
for mut orb in entity_nbt::orbs_from_nbt(&tag) {
self.next_entity += 1;
orb.id = self.next_entity;
self.orbs.push(orb);
}
}
"minecraft:arrow" => {
if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt(
&tag,
@@ -148,6 +148,7 @@ mod tests {
fn orb_at(x: f64, y: f64, z: f64) -> Taken {
let at = horizon_core::geometry::Vec3::new(x, y, z);
Taken::Orb(Box::new(ExperienceOrb {
id: 0,
position: at,
previous: at,
velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0),
+437 -40
View File
@@ -11,15 +11,17 @@ use horizon_client::{
Result,
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
containers::{BlockEntity, Furnace, FurnaceKind},
entities::{Experience, ItemEntity},
entities::{Experience, ExperienceOrb, ItemEntity},
hud::{HudBatch, rgba},
items::ItemStack,
mobs::{Mob, MobType},
menu::Input,
mobs::{Mob, MobType, Who},
motion::{MotionWorld, PlayerMotion},
net::{Event, Session},
save::SaveDir,
sprint::Keys,
streaming::{ChunkGenerator, Proto, Streaming},
tab_list::SPECTATOR,
world::World,
};
use horizon_core::{
@@ -65,8 +67,11 @@ struct Tracked {
}
/// Smooth an entity toward a new position over three ticks (InterpolationHandler).
#[derive(Clone, Copy)]
/// `LinearInterpolationHandler`'s target: a position and rotation (yRot,
/// xRot) reached in `steps` ticks.
struct Lerp {
target: [f64; 3],
rotation: Option<(f32, f32)>,
steps: u32,
}
@@ -106,6 +111,8 @@ pub(super) struct Remote {
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
lerps: HashMap<i32, Lerp>,
/// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it.
head_lerps: HashMap<i32, (f32, u32)>,
/// Item entities waiting for their item data.
pending_items: HashMap<i32, [f64; 3]>,
health: (f32, i32, f32),
@@ -293,6 +300,7 @@ impl Game<'_> {
use_target: None,
entities: HashMap::new(),
lerps: HashMap::new(),
head_lerps: HashMap::new(),
pending_items: HashMap::new(),
health: (20.0, 20, 5.0),
game_mode: 0,
@@ -606,6 +614,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.entities.clear();
r.lerps.clear();
r.head_lerps.clear();
r.pending_items.clear();
// A new ClientLevel: a new chunk storage, centred on 0, 0.
r.chunk_center = (0, 0);
@@ -799,6 +808,7 @@ impl Game<'_> {
0 => {
if me {
self.sleeping = None;
self.sleep_timer = 100;
}
return;
}
@@ -907,17 +917,33 @@ impl Game<'_> {
}
}
}
fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], yaw: f32, head: f32) {
/// `recreateFromPacket`: yRot and xRot from the packet, the body and head
/// both at its head yaw (LivingEntity).
fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], rotation: [f32; 3]) {
let [yaw, pitch, head] = rotation;
let at = Vec3::new(position[0], position[1], position[2]);
let mob_type = if kind == "minecraft:player" {
self.remote.as_ref().and_then(|r| r.player_type.clone())
} else {
self.res.mob_types.get(kind).cloned()
};
if kind == "minecraft:experience_orb" {
// Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData.
self.orbs.retain(|o| o.id != id as u32);
self.orbs.push(ExperienceOrb {
id: id as u32,
position: at,
previous: at,
velocity: Vec3::ZERO,
value: 1,
age: 0,
on_ground: false,
});
}
if let Some(t) = mob_type {
let mut mob = Mob::new(id as u32, t, at, head);
mob.body_yaw = yaw;
mob.previous_body_yaw = yaw;
(mob.yaw, mob.previous_yaw) = (yaw, yaw);
(mob.head_pitch, mob.previous_head_pitch) = (pitch, pitch);
mob.persistent = true;
self.mobs.retain(|m| m.id != id as u32);
self.mobs.push(mob);
@@ -942,14 +968,21 @@ impl Game<'_> {
rotation: Option<(f32, f32)>,
on_ground: bool,
) {
let mob = self.mobs.iter_mut().find(|m| m.id == id as u32);
if let Some(r) = self.remote.as_mut() {
if let Some(t) = r.entities.get_mut(&id) {
t.position = position;
}
// AbstractInterpolationHandler.interpolateTo: without a rotation,
// the one it was heading for (or has).
let rotation = rotation
.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation))
.or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch)));
r.lerps.insert(
id,
Lerp {
target: position,
rotation,
steps: 3,
},
);
@@ -957,20 +990,18 @@ impl Game<'_> {
*p = position;
}
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
if let Some(m) = mob {
m.on_ground = on_ground;
if let Some((yaw, pitch)) = rotation {
m.body_yaw = yaw;
m.head_pitch = pitch;
}
}
}
fn remove_entity(&mut self, id: i32) {
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
if let Some(r) = self.remote.as_mut() {
r.entities.remove(&id);
r.lerps.remove(&id);
r.head_lerps.remove(&id);
r.pending_items.remove(&id);
}
}
@@ -1220,8 +1251,8 @@ impl Game<'_> {
.map(str::to_owned)
})
.unwrap_or_default();
let yaw = horizon_protocol::buf::unpack_degrees(p.yaw);
let head = horizon_protocol::buf::unpack_degrees(p.head_yaw);
let rotation =
[p.yaw, p.pitch, p.head_yaw].map(horizon_protocol::buf::unpack_degrees);
if let Some(r) = self.remote.as_mut() {
if kind == "minecraft:player" {
r.level_players.insert(p.id, p.uuid);
@@ -1229,7 +1260,7 @@ impl Game<'_> {
r.level_players.remove(&p.id);
}
}
self.spawn_entity(p.id, &kind, p.position, yaw, head);
self.spawn_entity(p.id, &kind, p.position, rotation);
}
C::RemoveEntities(p) => {
for id in p.ids {
@@ -1280,9 +1311,11 @@ impl Game<'_> {
];
self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground);
}
// ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3).
C::RotateHead(p) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
m.yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw);
if let Some(r) = self.remote.as_mut() {
let yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw);
r.head_lerps.insert(p.id, (yaw, 3));
}
}
C::SetEntityData(p) => {
@@ -1310,12 +1343,31 @@ impl Game<'_> {
}
}
}
// 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) {
for (index, _, value) in &p.values {
if let (14, Value::OptPos(bed)) = (index, value) {
if bed.is_some() && self.sleeping.is_none() {
self.sleep_timer = 0;
}
self.sleeping = *bed;
}
}
}
for (index, _, value) in &p.values {
if *index == ITEM_ENTITY_ITEM
&& let Value::Item(stack) = value
{
self.remote_item_data(p.id, stack);
}
// ExperienceOrb.DATA_VALUE (the icon's size).
if *index == 8
&& let Value::Int(v) = value
&& let Some(o) = self.orbs.iter_mut().find(|o| o.id == p.id as u32)
{
o.value = (*v).max(0) as u32;
}
}
}
// ClientPacketListener.handleSetEquipment: what a mob or another
@@ -1342,10 +1394,13 @@ impl Game<'_> {
}
}
C::TakeItemEntity(p) => {
if self
.remote
.as_ref()
.is_some_and(|r| r.entity_id == p.player)
// An orb's sound comes from the server, at the orb.
let orb = self.orbs.iter().any(|o| o.id == p.item as u32);
if !orb
&& self
.remote
.as_ref()
.is_some_and(|r| r.entity_id == p.player)
&& let Some(eye) = self.eye_position()
{
let pitch = ((self.world.random.next_float() - self.world.random.next_float())
@@ -1356,17 +1411,20 @@ impl Game<'_> {
.play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch);
}
// ItemPickupParticle toward the collector (this player, another one or a mob).
let collector = if self
.remote
.as_ref()
.is_some_and(|r| r.entity_id == p.player)
{
super::pickups::Collector::Player
} else {
super::pickups::Collector::Mob(p.player as u32)
};
if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() {
let collector = if self
.remote
.as_ref()
.is_some_and(|r| r.entity_id == p.player)
{
super::pickups::Collector::Player
} else {
super::pickups::Collector::Mob(p.player as u32)
};
self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector);
} else if let Some(orb) = self.orbs.iter().find(|o| o.id == p.item as u32).cloned()
{
self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector);
}
self.remove_entity(p.item);
}
@@ -2192,7 +2250,10 @@ impl Game<'_> {
self.tick_hand();
self.tick_particles();
self.tick_client_effects();
// Player.tick's sleep counter (the darkening and the wake-up fade).
self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
let ghast_collisions = self.happy_ghast_player_collisions();
let pushed = self.remote_pushes();
let Some(player) = self.player.as_mut() else {
return Ok(());
};
@@ -2243,7 +2304,16 @@ impl Game<'_> {
);
player.yaw = self.yaw;
let dead = self.screen == Screen::Dead;
if !dead {
// LivingEntity.isImmobile: a sleeper lies still in the bed.
if let Some(head) = self.sleeping {
player.position = Vec3::new(
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
);
player.velocity = Vec3::ZERO;
} else if !dead {
player.velocity = player.velocity.add_vector(pushed);
MotionWorld {
entities: &ghast_collisions,
player,
@@ -2287,15 +2357,81 @@ impl Game<'_> {
self.tick_player_model();
if !dead {
self.remote_mining();
if self.right && self.use_delay == 0 && playing {
// Minecraft.handleKeybinds: no new use while an item is in use.
if self.right && self.use_delay == 0 && playing && self.using.is_none() {
self.remote_use();
self.use_delay = 4;
}
self.remote_tick_using();
}
self.remote_send_state(input);
self.send(S::ClientTickEnd(Empty));
Ok(())
}
/// 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
/// these pushes. `doPush(player)` is `player.push(entity)`.
fn remote_pushes(&self) -> Vec3 {
let (Some(p), Some(r)) = (self.player.as_ref(), self.remote.as_ref()) else {
return Vec3::ZERO;
};
// LivingEntity.isPushable: alive, no spectator, off ladders.
let feet = [
p.position.x.floor() as i32,
p.position.y.floor() as i32,
p.position.z.floor() as i32,
];
if self.screen == Screen::Dead
|| p.spectator
|| self.block_in_tag("minecraft:climbable", &self.block_name(feet))
{
return Vec3::ZERO;
}
let bounds = p.bounds();
let teams = self.mob_teams();
let mut push = Vec3::ZERO;
for m in &self.mobs {
let spectator = r
.level_players
.get(&(m.id as i32))
.and_then(|uuid| r.tab_players.get(uuid))
.is_some_and(|t| t.game_mode == SPECTATOR);
// Bats never push; a spectator has no physics; passengers of the
// same vehicle never push each other.
if !m.alive()
|| spectator
|| m.species() == horizon_client::mobs::Species::Bat
|| self
.riding
.is_some_and(|v| v == m.id || m.extra.mount == Some(v))
|| !m.bounds().intersects(bounds)
|| !horizon_client::scoreboard::pushable_by(
teams.of(Who::Mob(m.id)),
teams.of(Who::Player),
true,
)
{
continue;
}
// Entity.push(Entity), `this` the player.
let (mut xa, mut za) = (m.position.x - p.position.x, m.position.z - p.position.z);
let mut dd = xa.abs().max(za.abs());
if dd < f64::from(0.01_f32) {
continue;
}
dd = dd.sqrt();
xa /= dd;
za /= dd;
let pow = (1.0 / dd).min(1.0);
xa *= pow;
za *= pow;
xa *= f64::from(0.05_f32);
za *= f64::from(0.05_f32);
push = Vec3::new(push.x - xa, push.y, push.z - za);
}
push
}
/// ClientLevel.tickEntities; a frozen level only ticks the players
/// (`TickRateManager.isEntityFrozen`).
fn tick_remote_entities(&mut self, running: bool) {
@@ -2303,14 +2439,18 @@ impl Game<'_> {
return;
};
let mut lerps = std::mem::take(&mut r.lerps);
let head_lerps = &mut r.head_lerps;
let players = &r.level_players;
for m in &mut self.mobs {
if !running && !players.contains_key(&(m.id as i32)) {
let player = players.contains_key(&(m.id as i32));
if !running && !player {
continue;
}
m.previous = m.position;
m.previous_yaw = m.yaw;
m.previous_body_yaw = m.body_yaw;
m.previous_head_yaw = m.head_yaw;
m.previous_head_pitch = m.head_pitch;
m.previous_limb_speed = m.limb_speed;
m.age += 1;
if m.species() == horizon_client::mobs::Species::Rabbit {
@@ -2325,6 +2465,7 @@ impl Game<'_> {
if !m.alive() {
m.death_time += 1;
}
// Entity.commonTick: LinearInterpolationHandler.interpolate.
if let Some(l) = lerps.get_mut(&(m.id as i32))
&& l.steps > 0
{
@@ -2334,8 +2475,27 @@ impl Game<'_> {
m.position.y + (l.target[1] - m.position.y) / n,
m.position.z + (l.target[2] - m.position.z) / n,
);
if let Some((yaw, pitch)) = l.rotation {
let alpha = 1.0 / l.steps as f32;
m.yaw += wrap_degrees(yaw - m.yaw) * alpha;
m.head_pitch += (pitch - m.head_pitch) * alpha;
}
l.steps -= 1;
}
// LivingEntity.aiStep: the head's own interpolation.
if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32))
&& *steps > 0
{
m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32;
*steps -= 1;
}
// LivingEntity.tick's tickHeadTurn: a mob's BodyRotationControl,
// a player's body following its walk and look.
if player {
remote_player_head_turn(m);
} else if m.alive() {
m.body_rotation_tick();
}
// WalkAnimationState.update from the horizontal distance moved.
let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z);
let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0);
@@ -2345,6 +2505,21 @@ impl Game<'_> {
horizon_client::mobs::rabbit::post_tick(m);
}
}
for o in self.orbs.iter_mut().filter(|_| running) {
o.previous = o.position;
o.age += 1;
if let Some(l) = lerps.get_mut(&(o.id as i32))
&& l.steps > 0
{
let n = f64::from(l.steps);
o.position = Vec3::new(
o.position.x + (l.target[0] - o.position.x) / n,
o.position.y + (l.target[1] - o.position.y) / n,
o.position.z + (l.target[2] - o.position.z) / n,
);
l.steps -= 1;
}
}
for d in self.dropped.iter_mut().filter(|_| running) {
d.previous = d.position;
d.age += 1;
@@ -2361,6 +2536,7 @@ impl Game<'_> {
}
}
lerps.retain(|_, l| l.steps > 0);
head_lerps.retain(|_, (_, steps)| *steps > 0);
if let Some(r) = self.remote.as_mut() {
for (id, l) in lerps {
r.lerps.entry(id).or_insert(l);
@@ -2668,8 +2844,16 @@ impl Game<'_> {
location: [0.0, 1.0, 0.0],
secondary: sneaking,
}));
self.swing_arm();
return;
// Player.interactOn: another player passes, and the held item is
// used instead (Minecraft.startUseItem).
let player = self
.remote
.as_ref()
.is_some_and(|r| r.level_players.contains_key(&id));
if !player {
self.swing_arm();
return;
}
}
if let Some(hit) = self.pick() {
let seq = self.next_sequence();
@@ -2702,7 +2886,7 @@ impl Game<'_> {
return;
}
}
if self.held().is_some() {
if let Some(held) = self.held().cloned() {
let seq = self.next_sequence();
self.send(S::UseItem(play::UseItem {
hand: 0,
@@ -2710,6 +2894,44 @@ impl Game<'_> {
yaw: self.yaw,
pitch: self.pitch,
}));
// MultiPlayerGameMode.useItem runs the use here too: food starts
// being eaten (Consumable.startConsuming).
if let Some(info) = self.res.items.get(&held.item).cloned() {
self.start_eating(&info);
}
}
}
/// `LivingEntity.updatingUsingItem` for food on a server client: the
/// 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();
let food = stack
.as_ref()
.and_then(|s| self.res.items.get(&s.item))
.is_some_and(|i| i.consumable && i.food.is_some());
let (Some(stack), true) = (stack, food) else {
self.using = None;
return;
};
if !self.right || slot != self.selected || self.screen != Screen::Playing {
self.using = None;
return;
}
// Consumable.shouldEmitParticlesAndSounds, as in tick_used_item.
let duration = 32;
let remaining = duration - ticks.min(duration);
if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 {
self.eat_particles(&stack, 5);
}
if ticks + 1 >= duration {
self.using = None;
self.eat_particles(&stack, 16);
} else {
self.using = Some((slot, ticks + 1));
}
}
/// Left click: attack the targeted entity (MultiPlayerGameMode.attack).
@@ -2862,17 +3084,108 @@ impl Game<'_> {
let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return;
};
let input = if self.has_shift_down() { 1 } else { 0 };
self.remote_slot_click(internal, i8::from(right), input);
let input = if self.has_shift_down() {
Input::QuickMove
} else {
Input::Pickup
};
self.remote_menu_ops(&[(Some(internal), i32::from(right), input)]);
}
/// The server's open menu: its window id and menu type (0, "inventory"
/// when none is open).
fn remote_menu(&self) -> (i32, String) {
match self.remote.as_ref().and_then(|r| r.menu.clone()) {
Some((id, name)) => (id, name),
None => (0, "inventory".to_owned()),
}
}
/// `MultiPlayerGameMode.handleContainerInput` for each click of `ops` on
/// the server's open menu (a quick craft drag is several): the verified
/// menu engine predicts them on this client's copy, then each goes out as
/// a `ContainerClick` with the slots it changed and the carried stack
/// after it; the server corrects anything it sees differently. A menu the
/// 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 {
let (container, menu) = self.remote_menu();
let mut clicks = Vec::with_capacity(ops.len());
for &(slot, button, input) in ops {
let slot = match slot {
None => -999,
Some(internal) => {
match (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)) {
Some(s) => s as i16,
None => return false,
}
}
};
clicks.push((slot, button, input));
}
// Unpredicted: nothing changed, the carried stack as it is.
let mut sent: Vec<Predicted> = clicks
.iter()
.map(|&(slot, button, input)| (slot, button, input, Vec::new(), self.carried.clone()))
.collect();
// The engine's slot indices are the menu's own, as on the network.
self.menu_session(|m, env, _| {
let mut predicted = Vec::with_capacity(clicks.len());
for &(slot, button, input) in &clicks {
let before = menu_items(m);
if m.click(env, i32::from(slot), button, input).is_err() {
// The server throws on it too: nothing is predicted.
return Some(false);
}
let changed = changed_slots(&before, m);
predicted.push((slot, button, input, changed, m.carried.clone()));
}
sent = predicted;
Some(true)
});
self.send_clicks(container, sent);
true
}
/// A Shift double click on a server (`AbstractContainerScreen.mouseReleased`):
/// a predicted QUICK_MOVE for every slot the engine moves, each sent.
pub(super) fn remote_quick_move_all(&mut self, slot: usize, moved: &ItemStack) {
let (container, _) = self.remote_menu();
let mut sent: Vec<Predicted> = Vec::new();
self.menu_session(|m, env, to_menu| {
let clicked = to_menu(slot)?;
let mut before = menu_items(m);
let mut each = |m: &horizon_client::menu::Menu, t: usize| {
let changed = changed_slots(&before, m);
sent.push((t as i16, 0, Input::QuickMove, changed, m.carried.clone()));
before = menu_items(m);
};
Some(
m.quick_move_all_each(env, clicked, moved, &mut each)
.is_ok(),
)
});
self.send_clicks(container, sent);
}
fn send_clicks(&mut self, container: i32, clicks: Vec<Predicted>) {
let state = self.remote.as_ref().map_or(0, |r| r.state_id);
let hashed = |g: &Self, s: &Option<ItemStack>| g.to_network(s).map(|s| Hashed::of(&s));
for (slot, button, input, changed, carried) in clicks {
let changed = changed.iter().map(|(i, s)| (*i, hashed(self, s))).collect();
let carried = hashed(self, &carried);
self.send(S::ContainerClick(play::ContainerClick {
container,
state,
slot,
button: button as i8,
input: input_ordinal(input),
changed,
carried,
}));
}
}
/// A `ContainerClick` on game slot `internal` of the server's open menu
/// (`input` is the ContainerInput ordinal). False when the menu has no
/// such slot.
pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool {
let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) {
Some((id, name)) => (id, name),
None => (0, "inventory".to_owned()),
};
let (container, menu) = self.remote_menu();
let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal));
let Some(slot) = slot else { return false };
let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s));
@@ -3116,6 +3429,15 @@ impl Game<'_> {
.ok()?;
Some((rows, r.menu_title.clone().unwrap_or_default()))
}
/// ServerboundPlayerCommandPacket STOP_SLEEPING.
pub(super) fn remote_stop_sleeping(&mut self) {
let id = self.remote.as_ref().map_or(0, |r| r.entity_id);
self.send(S::PlayerCommand(play::PlayerCommand {
id,
action: 0,
data: 0,
}));
}
pub(super) fn remote_respawn(&mut self) {
self.send(S::ClientCommand(play::ClientCommand { action: 0 }));
}
@@ -3260,6 +3582,81 @@ impl Game<'_> {
}
}
/// `Mth.wrapDegrees`.
fn wrap_degrees(a: f32) -> f32 {
let a = a % 360.0;
if a >= 180.0 {
a - 360.0
} else if a < -180.0 {
a + 360.0
} else {
a
}
}
/// `LivingEntity.tick`'s body target and `tickHeadTurn` for another player:
/// the body turns toward where it walks (backwards when walking back), or to
/// the look while the arm swings, and stays within 50 degrees of the look.
fn remote_player_head_turn(m: &mut Mob) {
let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z);
let mut target = m.body_yaw;
if (dx * dx + dz * dz) as f32 > 0.002_500_000_2 {
let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0;
let facing = (wrap_degrees(m.yaw) - walk).abs();
target = if 95.0 < facing && facing < 265.0 {
walk - 180.0
} else {
walk
};
}
if m.anim.attack_anim > 0.0 {
target = m.yaw;
}
m.body_yaw += wrap_degrees(target - m.body_yaw) * 0.3;
let head = wrap_degrees(m.yaw - m.body_yaw);
if head.abs() > 50.0 {
m.body_yaw += head - head.signum() * 50.0;
}
}
/// A click sent to a server: its slot, button and input, the slots it
/// changed and the carried stack after it.
type Predicted = (
i16,
i32,
Input,
Vec<(i16, Option<ItemStack>)>,
Option<ItemStack>,
);
fn menu_items(m: &horizon_client::menu::Menu) -> Vec<Option<ItemStack>> {
(0..m.slot_count()).map(|i| m.slot(i).cloned()).collect()
}
/// The slots whose stack is no longer `before`'s (`ItemStack.matches`).
fn changed_slots(
before: &[Option<ItemStack>],
m: &horizon_client::menu::Menu,
) -> Vec<(i16, Option<ItemStack>)> {
(0..m.slot_count())
.filter(|&i| m.slot(i) != before.get(i).and_then(Option::as_ref))
.map(|i| (i as i16, m.slot(i).cloned()))
.collect()
}
/// ServerboundContainerClickPacket's `ContainerInput` ordinal.
pub(super) fn input_ordinal(input: Input) -> i32 {
match input {
Input::Pickup => 0,
Input::QuickMove => 1,
Input::Swap => 2,
Input::Clone => 3,
Input::Throw => 4,
Input::QuickCraft => 5,
Input::PickupAll => 6,
}
}
#[cfg(test)]
mod tests {
use super::Game;
@@ -324,7 +324,7 @@ impl Game<'_> {
)
.unwrap_or_else(|_| VoxelShape::empty())
}
fn block_in_tag(&self, tag: &str, block: &str) -> bool {
pub(super) fn block_in_tag(&self, tag: &str, block: &str) -> bool {
self.res
.items
.block_tags
+1 -9
View File
@@ -70,15 +70,7 @@ impl Game<'_> {
/// One ordinary click on a game slot. False when nothing took it.
pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool {
if self.remote.is_some() {
let ordinal = match input {
Input::Pickup => 0,
Input::QuickMove => 1,
Input::Swap => 2,
Input::Clone => 3,
Input::Throw => 4,
Input::QuickCraft => 5,
Input::PickupAll => 6,
};
let ordinal = super::remote::input_ordinal(input);
return self.remote_slot_click(slot, button as i8, ordinal);
}
if !self.menu_click(Some(slot), button, input) {
+12
View File
@@ -69,6 +69,14 @@ pub struct Guest {
pub fall_flying: bool,
pub flying: bool,
pub sleeping: bool,
/// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`),
/// `Player.sleepCounter`, and the bed last told to the player itself.
pub bed: Option<[i32; 3]>,
pub sleep_timer: u32,
pub sent_bed: Option<[i32; 3]>,
/// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`),
/// None for the world spawn.
pub spawn: Option<[f64; 3]>,
/// Pending ClientboundPlayerPositionPacket id; movement is ignored until
/// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient).
pub awaiting_teleport: Option<(i32, [f64; 3])>,
@@ -204,6 +212,10 @@ impl Guest {
fall_flying: false,
flying: false,
sleeping: false,
bed: None,
sleep_timer: 0,
sent_bed: None,
spawn: None,
awaiting_teleport: None,
teleport_counter: 0,
teleport_tick: 0,
+36 -1
View File
@@ -1515,10 +1515,44 @@ impl Hub {
}
}
/// ServerPlayer.stopSleepInBed: the wake-up animation goes to the player
/// and those around, the pose is standing again and the sleep counter
/// starts the wake-up fade (100).
pub fn wake(&mut self, i: usize) {
let g = &mut self.guests[i];
if g.bed.take().is_none() && !g.sleeping {
return;
}
g.sleeping = false;
g.sleep_timer = 100;
let (id, at) = (g.entity_id, g.position);
// ClientboundAnimatePacket.WAKE_UP.
self.broadcast_near(
at,
128.0,
&C::Animate(play::Animate { id, action: 0 }),
None,
);
}
// ---- per-player state ------------------------------------------------
/// ServerPlayer.doTick: health, food, experience and the inventory menu.
fn sync_player_state(&mut self, i: usize) {
// LivingEntity.startSleeping / stopSleeping: the pose and the bed go
// to the player too (its client lies down in the bed from them).
let g = &mut self.guests[i];
if g.bed != g.sent_bed {
g.sent_bed = g.bed;
let pose = if g.bed.is_some() { 2 } else { 0 };
g.send(&C::SetEntityData(play::SetEntityData {
id: g.entity_id,
values: vec![
(6, serializer::POSE, Value::Id(pose)),
(14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(g.bed)),
],
}));
}
// ServerEntity.sendDirtyEntityData on the player's first tick: the
// health its creation set is still dirty, and goes to the player too.
if self.guests[i].sent_health.is_none() {
@@ -1767,7 +1801,8 @@ impl Hub {
1 => self.guests[i].sprinting = true,
2 => self.guests[i].sprinting = false,
6 => self.guests[i].fall_flying = true,
0 => self.guests[i].sleeping = false,
// STOP_SLEEPING.
0 => self.wake(i),
_ => {}
},
S::Chat(c) => {
@@ -69,6 +69,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects);
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]);
guest.saved = level.player_extra.clone();
guest.recipe_book = level.recipe_book.clone();
guest.dimension = match level.dimension.as_str() {
@@ -129,6 +130,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.game_mode = guest.game_mode;
level.creative = guest.game_mode == 1;
level.selected_slot = guest.selected as i32;
level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]);
level.on_ground = guest.on_ground;
level.player_extra = guest.saved.clone();
level.recipe_book = guest.recipe_book.clone();
+13
View File
@@ -1668,6 +1668,18 @@ impl Menu {
env: &Env,
clicked: usize,
moved: &ItemStack,
) -> Result<(), &'static str> {
self.quick_move_all_each(env, clicked, moved, &mut |_, _| {})
}
/// `quick_move_all`, calling `each` with the menu and the slot after each
/// QUICK_MOVE (a server's client sends every one of them).
pub fn quick_move_all_each(
&mut self,
env: &Env,
clicked: usize,
moved: &ItemStack,
each: &mut dyn FnMut(&Self, usize),
) -> Result<(), &'static str> {
if clicked >= self.slots.len() || !self.can_take_for_pick_all(clicked) {
return Ok(());
@@ -1680,6 +1692,7 @@ impl Menu {
&& self.quick_replace(t, moved, env)
{
self.click(env, t as i32, 0, Input::QuickMove)?;
each(self, t);
}
}
Ok(())
+3
View File
@@ -1400,6 +1400,9 @@ pub struct PlayerView {
/// The mobs on the player's team (`isAlliedTo`): combat targeting
/// leaves the player alone.
pub allies: std::sync::Arc<std::collections::HashSet<u32>>,
/// A LAN guest: its own client moves it, and touching mobs push it there
/// (`EntitySelector.pushableBy` on the client).
pub remote: bool,
}
pub struct MobWorld<'a> {
pub world: &'a World,
+8 -4
View File
@@ -822,10 +822,14 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
za *= pow;
xa *= f64::from(0.05_f32);
za *= f64::from(0.05_f32);
events.push(MobEvent::Push {
target: who,
velocity: [-xa, 0.0, -za],
});
// A guest's server-side push never reaches its client (ServerPlayer
// motion is synced only when hurt): its client pushes it itself.
if who != Who::Player || w.player.as_ref().is_none_or(|p| !p.remote) {
events.push(MobEvent::Push {
target: who,
velocity: [-xa, 0.0, -za],
});
}
if self_pushable {
m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za);
}
+225 -4
View File
@@ -30,6 +30,18 @@ address. The script then checks, from both sides, what a guest's game used to ge
tree (Tab), and runs what it completed;
- recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it
places a log in the inventory's crafting grid (the server places it).
- feedback: the guest's command feedback names the guest and shows the numbers.
- clicks: with real mouse presses (not click-slot, which skips the screen's press and drag
handling), the guest puts a stack into a chest and a furnace, drags planks across
its crafting grid and gathers a stack with a double click; the server has each.
- sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it
gets up with Escape, and once the host sleeps too the night ends and both wake.
- push: a cow standing in the guest pushes it just clear of the cow (the guest's own client
pushes it, as in vanilla), not ever faster across the ground.
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
counts up) and the server eats one loaf and feeds the guest.
- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the
guest their points (not the host).
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
both sides go to --out (host-*.png, guest-*.png).
@@ -50,6 +62,7 @@ import shutil
import subprocess
import sys
import tempfile
import threading
import time
import zlib
from pathlib import Path
@@ -61,7 +74,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'effects', 'portals']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'effects', 'portals']
class Game:
@@ -584,6 +597,91 @@ def check_containers(host, guest, out):
return {'ender': ender, 'double': double, 'taken': taken}
def slot_point(game, slot):
"""The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N)."""
for w in game.raw('ui')['widgets']:
if w.get('id') == f'slot-{slot}':
x, y, width, height = w['bounds']
return x + width / 2, y + height / 2
raise Failed(f'no slot {slot} on the screen')
def mouse(game, *slots, right=False):
"""Press over the first slot, move over the others and release: one click, or a drag."""
points = [f'{v:.1f}' for s in slots for v in slot_point(game, s)]
game.raw('drag-at', *(['right'] if right else []), *points)
game.wait(4)
def hotbar_slot(game, item):
return next(s['slot'] for s in game('inventory')['hotbar'] if s and s.get('item') == item)
def check_clicks(host, guest, out):
guest('command', command='gamemode survival')
guest('command', command='clear @s')
guest('command', command='give @s minecraft:cobblestone 10')
guest('command', command='give @s minecraft:coal 3')
guest('command', command='give @s minecraft:raw_iron 2')
guest('command', command='give @s minecraft:oak_planks 2')
guest.wait(10)
x, y, z = (int(v // 1) for v in pos_of(guest))
chest, furnace = (x, y, z + 2), (x, y, z - 2)
guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
guest('command', command=f'setblock {furnace[0]} {furnace[1]} {furnace[2]} minecraft:furnace')
guest.wait(10)
# Pick the cobblestone up and put it down in the chest's first slot.
guest.raw('interact', *chest)
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
guest.wait(10)
mouse(guest, hotbar_slot(guest, 'minecraft:cobblestone'))
mouse(guest, 300)
guest.wait(10)
guest.shot(out, 'clicks-chest')
guest.raw('key', 'esc', 'tap')
guest.wait(10)
in_chest, _ = open_container(guest, chest, out, 'clicks-chest-after')
# Coal into the fuel slot, raw iron into the input.
guest.raw('interact', *furnace)
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
guest.wait(10)
mouse(guest, hotbar_slot(guest, 'minecraft:coal'))
mouse(guest, 301)
mouse(guest, hotbar_slot(guest, 'minecraft:raw_iron'))
mouse(guest, 300)
guest.wait(10)
guest.shot(out, 'clicks-furnace')
guest.raw('key', 'esc', 'tap')
guest.wait(10)
# Opening the furnace again resends the whole menu: the server's own view.
in_furnace, _ = open_container(guest, furnace, out, 'clicks-furnace-after')
# Two planks dragged over the 2x2 grid's left column: one each, four sticks.
guest.raw('key', 'e', 'tap')
guest.raw('wait-for', 'screen', 'inventory')
guest.wait(5)
mouse(guest, hotbar_slot(guest, 'minecraft:oak_planks'))
mouse(guest, 100, 102)
guest.wait(10)
grid = {s['slot']: (s.get('item'), s.get('count')) for s in guest('screen').get('slots', [])
if s.get('slot') in (100, 102, 200) and s.get('item')}
guest.shot(out, 'clicks-drag')
guest.raw('click-slot', 200, 'shift')
guest.wait(10)
guest.raw('key', 'esc', 'tap')
guest.wait(10)
# The chest's menu brings the whole inventory as the server has it.
open_container(guest, chest, out, 'clicks-inventory')
counts = guest('inventory')['counts']
for at in (chest, furnace):
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
assert in_chest == {0: 'minecraft:cobblestone'}, f'the chest holds {in_chest} after the guest put cobblestone in'
assert in_furnace == {0: 'minecraft:raw_iron', 1: 'minecraft:coal'}, f'the furnace holds {in_furnace}'
assert grid.get(100) == ('minecraft:oak_planks', 1) and grid.get(102) == ('minecraft:oak_planks', 1), \
f'the drag left the grid as {grid}'
assert counts.get('minecraft:stick') == 4 and 'minecraft:cobblestone' not in counts, f'inventory after: {counts}'
return {'chest': in_chest, 'furnace': in_furnace, 'grid': grid, 'inventory': counts}
def check_feedback(host, guest, out):
x, y, z = (round(v, 1) for v in pos_of(guest))
guest('command', command='item replace entity @s weapon.mainhand with minecraft:stick')
@@ -824,13 +922,136 @@ def check_trials(host, guest, out):
return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)}
def bed_at(game, foot):
"""A bed whose foot is at `foot`, its head one block east."""
x, y, z = foot
game('command', command=f'setblock {x} {y} {z} minecraft:red_bed[facing=east,part=foot]')
game('command', command=f'setblock {x + 1} {y} {z} minecraft:red_bed[facing=east,part=head]')
return [x + 1, y, z]
def check_sleep(host, guest, out):
for g in (host, guest):
g('command', command='gamemode survival')
host('command', command='time set midnight')
gx, gy, gz = (int(v // 1) for v in pos_of(guest))
hx, hy, hz = (int(v // 1) for v in pos_of(host))
guest_bed = bed_at(guest, (gx, gy, gz + 2))
host_bed = bed_at(host, (hx, hy, hz + 2))
guest.wait(10)
guest.raw('interact', *guest_bed)
guest.wait(10)
asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'),
'server': host.raw('lan', 'status')['guests'][0].get('sleeping')}
guest.shot(out, 'sleep-guest')
# Alone in bed: still night 120 ticks later (everyone must sleep).
guest.wait(120)
night = host('state')['time']['time_of_day']
# Escape gets the guest up (InBedChatScreen), then back to bed.
guest.raw('key', 'esc', 'tap')
guest.wait(10)
up = guest('state').get('sleeping')
guest.raw('interact', *guest_bed)
host.raw('interact', *host_bed)
host.wait(130)
after = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'),
'time': host('state')['time']['time_of_day']}
guest.shot(out, 'sleep-morning')
for at in (guest_bed, host_bed):
guest('command', command=f'fill {at[0] - 1} {at[1]} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air')
host('command', command='time set day')
detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after}
assert asleep['guest'] == guest_bed and asleep['server'] == guest_bed, f'the guest is not in its bed: {detail}'
assert asleep['host'] is None, f'the guest\'s bed put the host to sleep: {detail}'
assert 13000 < night < 23000, f'one of two players asleep ended the night: {detail}'
assert up is None, f'Escape did not get the guest up: {detail}'
assert after['guest'] is None and after['host'] is None and after['time'] < 1000, f'no morning: {detail}'
return detail
def check_push(host, guest, out):
guest('command', command='gamemode survival')
x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest))
guest('command', command=f'tp @s {x} {y - 0.5} {z}')
guest.wait(20)
x, y, z = pos_of(guest)
# A cow that doesn't walk, 0.3 east of the guest: the two boxes overlap until their centres are
# 0.75 apart, so the push stops a fraction of a block away.
guest('command', command=f'summon minecraft:cow {x + 0.3:.2f} {y:.2f} {z:.2f} {{NoAI:1b}}')
guest.wait(60)
nx, _, nz = pos_of(guest)
guest.shot(out, 'push')
guest('command', command='kill @e[type=minecraft:cow]')
moved = ((nx - x) ** 2 + (nz - z) ** 2) ** 0.5
detail = {'from': [round(x, 3), round(z, 3)], 'to': [round(nx, 3), round(nz, 3)], 'moved': round(moved, 3)}
assert nx < x, f'the cow did not push the guest west: {detail}'
assert moved < 1.5, f'the cow pushed the guest too far: {detail}'
return detail
def check_eat(host, guest, out):
guest('command', command='gamemode survival')
guest('command', command='clear @s')
# Hungry: the eating needs food below 20 (Player.canEat).
guest('command', command='effect give @s minecraft:hunger 3 255')
guest.wait(70)
guest('command', command='effect clear @s')
guest('command', command='give @s minecraft:bread 3')
guest.wait(5)
guest.raw('select', 'minecraft:bread')
hungry = guest('state')['player']['food']
# use-item --hold returns once released: watch the guest's screen meanwhile.
hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.2))
hold.start()
using = []
for _ in range(4):
time.sleep(0.2)
using.append(guest('state').get('using'))
guest.shot(out, 'eat')
hold.join()
guest.wait(10)
fed = guest('state')['player']['food']
left = guest('inventory')['counts'].get('minecraft:bread', 0)
detail = {'hungry': hungry, 'fed': fed, 'bread': left, 'using': using, 'after': guest('state').get('using')}
assert hungry < 20, f'the guest is not hungry: {detail}'
ticks = [u['ticks'] for u in using if u]
assert len(ticks) >= 3 and ticks == sorted(ticks) and ticks[-1] > ticks[0], f'no eating on the guest\'s screen: {detail}'
assert left == 2 and fed > hungry, f'the server did not eat one loaf: {detail}'
assert detail['after'] is None, f'still eating after the release: {detail}'
return detail
def check_xp(host, guest, out):
for g in (host, guest):
g('command', command='gamemode survival')
g('command', command='xp set @s 0 levels')
g('command', command='xp set @s 0 points')
guest.wait(10)
x, y, z = pos_of(guest)
# Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs
# follow from): they fly to the guest.
for _ in range(3):
guest('command', command=f'summon minecraft:experience_orb {x + 4:.2f} {y + 0.5:.2f} {z:.2f} {{Value:7s}}')
guest.wait(2)
seen = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0)
guest.shot(out, 'xp-orbs')
guest.wait(60)
xp = guest('state')['player']['xp']
host_xp = host('state')['player']['xp']
left = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0)
detail = {'seen': seen, 'guest': xp, 'host': host_xp, 'left': left}
# ExperienceOrb.scanForMerges: orbs of one value side by side can merge into one.
assert 1 <= seen <= 3, f'the guest saw {seen} orbs: {detail}'
assert xp['total'] == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}'
assert host_xp['total'] == 0, f'the host took the orbs: {detail}'
assert left == 0, f'orbs left on the guest\'s screen: {detail}'
return {'seen': seen, 'guest': xp, 'host': host_xp}
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands,
'recipes': check_recipes,
'trials': check_trials,
'walls': check_walls, 'effects': check_effects, 'portals': check_portals}
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
'effects': check_effects, 'portals': check_portals, 'clicks': check_clicks,
'sleep': check_sleep, 'push': check_push, 'eat': check_eat,
'xp': check_xp}
def run(ctl, out, resources, checks):