diff --git a/crates/horizon-client/src/attribute_updates.rs b/crates/horizon-client/src/attribute_updates.rs index b81db5835..1dcc21028 100644 --- a/crates/horizon-client/src/attribute_updates.rs +++ b/crates/horizon-client/src/attribute_updates.rs @@ -22,6 +22,11 @@ impl PlayerMotion { pub fn refresh_attributes(&mut self) -> Result<()> { live_updates::refresh(self) } + /// `Player.internalSetAbsorptionAmount`: the amount as given, unclamped + /// (the saved `AbsorptionAmount`, or what a client's server sent). + pub fn internal_set_absorption(&mut self, value: f32) -> Result<()> { + self.store_absorption(value) + } } impl HealthWorld for PlayerMotion { type Error = Box; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..d689ad8fc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9516,6 +9516,7 @@ impl Game<'_> { if let Some(p) = &self.player { level.position = Some([p.position.x, p.position.y, p.position.z]); level.health = p.health.health(); + level.absorption = p.health.absorption(); let extra = level .player_extra .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..b30adca5c 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -459,6 +459,8 @@ impl Game<'_> { "sneaking": self.keys.contains(&KeyCode::ShiftLeft), "sprinting": self.keys.contains(&KeyCode::ControlLeft), "health": p.health.health(), + "absorption": p.health.absorption(), + "air": p.air, "food": p.health.food.food, "saturation": p.health.food.saturation, "xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total }, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..0ea2a6faa 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -393,6 +393,9 @@ impl Game<'_> { "sneaking": g.sneaking, "sleeping": g.bed, "health": g.health, + // The server's body: its air supply and golden hearts. + "air": g.motion.as_ref().map(|m| m.air), + "absorption": g.motion.as_ref().map(|m| m.health.absorption()), // FoodData: food level, saturation and exhaustion. "food": [ f64::from(g.food), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..65cbf2e5f 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -217,6 +217,12 @@ impl Game<'_> { host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + // The saved golden hearts go on the first body of a player who + // has been here before. + let saved = host.hub.guests[i].saved_absorption.take(); + if let (Some(m), Some(amount)) = (host.hub.guests[i].motion.as_mut(), saved) { + let _ = m.internal_set_absorption(amount); + } 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; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5461a4cd0..70096277f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1867,11 +1867,27 @@ impl Game<'_> { // 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; + match (index, value) { + (14, Value::OptPos(bed)) => { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; } - self.sleeping = *bed; + // Entity.DATA_AIR_SUPPLY_ID and + // Player.DATA_PLAYER_ABSORPTION_ID: the bubbles + // and golden hearts the server's player has. + (1, Value::Int(air)) => { + if let Some(pl) = self.player.as_mut() { + pl.air = *air; + } + } + (17, Value::Float(amount)) => { + if let Some(pl) = self.player.as_mut() { + let _ = pl.internal_set_absorption(*amount); + } + } + _ => {} } } } @@ -2997,6 +3013,13 @@ impl Game<'_> { ); let was_flying = player.flying; player.yaw = self.yaw; + // As the window's own tick has them: the helmet's Respiration + // (decreaseAirSupply) and the dimension's FAST_LAVA, the Nether's + // stronger lava current. + player.respiration = self.armor[0] + .as_ref() + .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); + player.fluids.fast_lava = self.dim == Dim::Nether; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. if let Some(head) = self.sleeping { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 1916344bb..3c5d4b50c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -149,6 +149,9 @@ pub struct Guest { /// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots). pub ender_items: Vec>, pub health: f32, + /// The saved `AbsorptionAmount`, until the player's first body on the + /// server takes it (the body holds the live amount). + pub saved_absorption: Option, pub food: i32, pub saturation: f32, pub xp_level: i32, @@ -168,6 +171,10 @@ pub struct Guest { /// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`. pub sent_health: Option<(f32, i32, bool)>, pub sent_xp: Option<(f32, i32, i32)>, + /// The air supply and absorption the player's client was last sent + /// (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID); their + /// defaults until either changes. + pub sent_air: (i32, f32), /// Where the player last died (Player.lastDeathLocation), sent with the respawn. pub last_death: Option<[i32; 3]>, /// The last action sequence to acknowledge at the next tick (-1: none). @@ -280,6 +287,7 @@ impl Guest { craft_result: None, ender_items: vec![None; 27], health: 20.0, + saved_absorption: None, food: 20, saturation: 5.0, xp_level: 0, @@ -292,6 +300,7 @@ impl Guest { menu_state: 0, sent_health: None, sent_xp: None, + sent_air: (300, 0.0), last_death: None, ack_up_to: std::cell::Cell::new(-1), sent_selected: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index bf66f979b..1455e60b8 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1755,6 +1755,27 @@ impl Hub { })); } } + // ServerEntity.sendDirtyEntityData: the air supply and the absorption + // amount the server's body changed go to the player, whose HUD draws + // them (bubbles, golden hearts). + let g = &mut self.guests[i]; + if let Some(m) = g.motion.as_ref() { + let now = (m.air, m.health.absorption()); + let mut values = Vec::new(); + if now.0 != g.sent_air.0 { + values.push((1, serializer::INT, Value::Int(now.0))); + } + if now.1.to_bits() != g.sent_air.1.to_bits() { + values.push((17, serializer::FLOAT, Value::Float(now.1))); + } + if !values.is_empty() { + g.sent_air = now; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values, + })); + } + } // Sent when the health or the food level changes, or the saturation // reaches or leaves zero; a dead player's health of 0 too. let g = &mut self.guests[i]; @@ -2465,9 +2486,11 @@ impl Hub { global: false, })); } - // lastSentExp, lastSentHealth and lastSentFood. + // lastSentExp, lastSentHealth and lastSentFood; the client's new + // player starts with the default air and no absorption. g.sent_health = None; g.sent_xp = None; + g.sent_air = (300, 0.0); let (cx, cz) = g.chunk(); g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { x: cx, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..6a26306fb 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -61,6 +61,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.head_yaw = guest.yaw; guest.on_ground = level.on_ground; guest.health = level.health; + guest.saved_absorption = Some(level.absorption); guest.food = level.food; guest.saturation = level.saturation; guest.xp_level = level.xp_level; @@ -123,6 +124,12 @@ pub fn store(guest: &Guest, level: &mut Level) { level.dimension = guest.dimension.clone(); level.rotation = [guest.yaw, guest.pitch]; level.health = guest.health; + level.absorption = guest + .motion + .as_ref() + .map_or(guest.saved_absorption.unwrap_or(0.0), |m| { + m.health.absorption() + }); level.food = guest.food; level.saturation = guest.saturation; level.xp_level = guest.xp_level; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..c0c882e0f 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -338,6 +338,8 @@ impl PlayerMotion { .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; self.set_health(level.health, false)?; + // LivingEntity.readAdditionalSaveData: internalSetAbsorptionAmount. + self.internal_set_absorption(level.absorption)?; self.health.food.food = level.food; self.health.food.saturation = level.saturation; self.flying = level.flying; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0cfe3c585..2fbb04dc4 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2266,6 +2266,8 @@ pub struct Level { pub position: Option<[f64; 3]>, pub rotation: [f32; 2], pub health: f32, + /// LivingEntity `AbsorptionAmount`: the golden hearts left. + pub absorption: f32, pub food: i32, pub saturation: f32, /// (slot, item, count, damage): 0..36 inventory, 100..103 armor (feet..head), 150 offhand. @@ -2455,6 +2457,7 @@ impl Level { } self.motion = read_doubles::<3>(p.get("Motion")).unwrap_or_default(); self.health = f("Health").map_or(20.0, |v| v as f32); + self.absorption = f("AbsorptionAmount").map_or(0.0, |v| v as f32); self.food = n("foodLevel").map_or(20, |v| v as i32); self.saturation = f("foodSaturationLevel").map_or(5.0, |v| v as f32); self.food_exhaustion = f("foodExhaustionLevel").unwrap_or(0.0) as f32; @@ -2626,6 +2629,7 @@ impl Level { ("OnGround", Tag::Byte(i8::from(self.on_ground))), ("fall_distance", Tag::Double(self.fall_distance.to_bits())), ("Health", Tag::Float(self.health.to_bits())), + ("AbsorptionAmount", Tag::Float(self.absorption.to_bits())), ("foodLevel", Tag::Int(self.food)), ("foodSaturationLevel", Tag::Float(self.saturation.to_bits())), ( @@ -2731,7 +2735,6 @@ impl Level { ("seenCredits", Tag::Byte(0)), ("HurtTime", Tag::Short(0)), ("DeathTime", Tag::Short(0)), - ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ] { map.entry(key.into()).or_insert(value); @@ -4114,6 +4117,7 @@ mod tests { position: Some([1.5, 70.0, -3.25]), rotation: [90.0, 10.0], health: 17.0, + absorption: 5.0, food: 15, saturation: 2.5, inventory: vec![ @@ -4144,6 +4148,7 @@ mod tests { assert_eq!(back.position, Some([1.5, 70.0, -3.25])); assert_eq!(back.rotation, [90.0, 10.0]); assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5)); + assert_eq!(back.absorption, 5.0); let mut inv = back.inventory.clone(); inv.sort(); assert_eq!( @@ -4178,10 +4183,13 @@ mod tests { let mut again = Level { player_extra: Some(extra), ender_items: ender, + // The live amount, not the one the loaded compound held (#1307). + absorption: 2.0, ..back }; again.write(&dir).unwrap(); let third = Level::read(&dir).unwrap(); + assert_eq!(third.absorption, 2.0); assert!(matches!( third .player_extra diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..a4fdafe71 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,12 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- absorption: the host and the guest each take Absorption II and a hit of 3: their own HUD has the + server's golden hearts, 8 then 5 (#1306). +- breath: the host and the guest each stay underwater for 15 s in a Respiration III helmet: their + own bubbles follow the server's air, which the enchantment makes last (#1304). +- lava: (--server-thread) the host and the guest each stand in a Nether lava current with Fire + Resistance, which pushes them at the Nether's strength (#1309). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +178,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'absorption', 'breath', 'lava'] class Game: @@ -2297,6 +2303,117 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def server_player(host, game): + """The player's entry on the server: the guest's in the host's `lan status`, on the server + thread the host's too; the host's own world otherwise.""" + if game is host and not SERVER_THREAD: + return own(host) + name = GUEST_NAME if game is not host else host.player + return next(g for g in host.raw('lan', 'status')['guests'] if g['name'] == name) + + +def check_absorption(host, guest, out): + """Absorption II's golden hearts on each player's own HUD: 8 of them, and 5 once a hit of 3 took + its share: the client shows what the server's player has (#1306).""" + seen = {} + for game in (host, guest): + game('command', command='gamemode survival') + game('command', command='effect give @s minecraft:absorption 120 1') + game.wait(10) + given = own(game)['absorption'] + game('command', command='damage @s 3 minecraft:generic') + game.wait(20) + me = own(game) + server = server_player(host, game) + game.shot(out, 'absorption') + game('command', command='effect clear @s minecraft:absorption') + seen[game.name] = {'given': given, 'left': me['absorption'], 'health': me['health'], + 'server': server.get('absorption')} + for name, s in seen.items(): + assert s['given'] == 8.0 and s['left'] == 5.0 == s['server'] and s['health'] == 20.0, \ + f'{name}: {seen}' + return seen + + +def check_breath(host, guest, out): + """Underwater in a Respiration III helmet for 15 s: the enchantment makes the air last on the + server, and each player's own bubbles follow the server's air (#1304).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s armor.head with ' + 'minecraft:diamond_helmet[minecraft:enchantments={"minecraft:respiration":3}]') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:stone') + game('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} minecraft:water') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + host.wait(300) + for game in (host, guest): + game.shot(out, 'breath') + seen[game.name] = {'own': own(game)['air'], 'server': server_player(host, game).get('air')} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='item replace entity @s armor.head with minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone') + guest.wait(40) + # 300 ticks lose about 75 of the 300 with Respiration III, all of it without. + for name, s in seen.items(): + assert s['server'] > 150 and abs(s['own'] - s['server']) <= 10, f'{name}: {seen}' + return seen + + +def check_lava(host, guest, out): + """(--server-thread) Standing in a settled Nether lava current with Fire Resistance: the + Nether's FAST_LAVA pushes each player about three times as hard as the Overworld's (#1309).""" + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + seen = {} + back = {g.name: pos_of(g) for g in (host, guest)} + try: + for game, z in ((host, 0), (guest, 6)): + game('command', command=f'execute in minecraft:the_nether run tp @s 0.5 100 {z + 0.5}') + state = wait_dimension(game, 'minecraft:the_nether', 600) + assert state.get('dimension') == 'minecraft:the_nether', f'{game.name} is in {state.get("dimension")}' + game.wait(40) + # A one-wide obsidian channel along x: a source at x = -3, the current flowing east. + game('command', command=f'fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air') + game('command', command=f'fill -5 98 {z - 1} 6 98 {z + 1} minecraft:obsidian') + game('command', command=f'fill -5 99 {z - 1} 6 99 {z - 1} minecraft:obsidian') + game('command', command=f'fill -5 99 {z + 1} 6 99 {z + 1} minecraft:obsidian') + game('command', command=f'fill -4 99 {z} -4 99 {z} minecraft:obsidian') + game('command', command='effect give @s minecraft:fire_resistance 120 0 true') + game('command', command='gamemode survival') + game('command', command=f'setblock -3 99 {z} minecraft:lava') + host.wait(100) + for game, z in ((host, 0), (guest, 6)): + game('command', command=f'tp @s 0.5 99 {z + 0.5}') + host.wait(60) + for game, z in ((host, 0), (guest, 6)): + v = own(game)['velocity'] + seen[game.name] = {'vx': v[0], 'level': game.raw('block', 0, 99, z).get('state')} + game.shot(out, 'lava') + finally: + for game, z in ((host, 0), (guest, 6)): + host('command', command=f'execute in minecraft:the_nether run fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air') + x, y, zz = back[game.name] + game('command', command='effect clear @s minecraft:fire_resistance') + game('command', command=f'execute in minecraft:overworld run tp @s {x:.2f} {y:.2f} {zz:.2f}') + for game in (host, guest): + wait_dimension(game, 'minecraft:overworld', 600) + guest.wait(40) + # The Overworld's current settles at about 0.0047 a tick, the Nether's at about 0.014. + for name, s in seen.items(): + assert s['vx'] > 0.009, f'{name}: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3192,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava} def run(ctl, out, resources, checks):