diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 3fa6e68a1..4ceafb3d0 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -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, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index bf02f689f..d627dc363 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -943,6 +943,7 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec { }; 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, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a74f1677e..7d6b4a992 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7393,7 +7393,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( @@ -7457,13 +7459,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; ( @@ -7476,7 +7494,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 { @@ -7510,19 +7540,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. diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 1995efbf4..3ca938d6a 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -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), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 156659ab3..57c7b9ee0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -715,7 +715,7 @@ impl Game<'_> { /// Mobs and items as the entities guests track. fn lan_entities(&self, hub: &mut Hub) -> Vec { - 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); @@ -753,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 } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index a21fe88da..68b29a360 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -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); @@ -1131,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; @@ -1488,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 = 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, diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 96d879f13..27fe36694 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -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, diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs index 2729dc98f..1e19bcfc3 100644 --- a/crates/horizon-client/src/game/pickups.rs +++ b/crates/horizon-client/src/game/pickups.rs @@ -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), diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 940824bcd..991bc42b2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -11,7 +11,7 @@ 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, menu::Input, @@ -927,6 +927,19 @@ impl Game<'_> { } 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.yaw, mob.previous_yaw) = (yaw, yaw); @@ -983,6 +996,7 @@ impl Game<'_> { } 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); @@ -1347,6 +1361,13 @@ impl Game<'_> { { 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 @@ -1373,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()) @@ -1387,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); } @@ -2478,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; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index df565e55f..b1e7ec098 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -40,6 +40,8 @@ address. The script then checks, from both sides, what a guest's game used to ge 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). @@ -72,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', 'clicks', 'sleep', 'push', 'eat', '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: @@ -964,6 +966,7 @@ def check_sleep(host, guest, out): 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)) @@ -981,7 +984,9 @@ def check_push(host, guest, out): 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') @@ -1000,6 +1005,7 @@ def check_eat(host, guest, out): 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')} @@ -1011,13 +1017,41 @@ def check_eat(host, guest, out): 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, 'clicks': check_clicks, - 'sleep': check_sleep, 'push': check_push, 'eat': check_eat} + 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, + 'xp': check_xp} def run(ctl, out, resources, checks):