diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 85107c1cb..9c90e8ebf 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -898,15 +898,9 @@ impl BlockEntityRenderer { pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) } - /// BannerRenderer submits the support and animated flag once for crumbling. - pub fn render_banner_breaking( - &self, - scene: &Scene, - pos: [i32; 3], - state: u32, - out: &mut Vec, - ) { - if !matches!(self.kind(state), Kind::Banner { .. }) { + /// ChestRenderer and BannerRenderer submit their animated models for crumbling. + pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { return; } let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) @@ -1098,7 +1092,7 @@ impl BlockEntityRenderer { ChestPart::Left => "double_chest_left", ChestPart::Right => "double_chest_right", }; - let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { + let Some(model) = self.models.get(model) else { return; }; let (open, other) = self.chest_openness( @@ -1719,18 +1713,28 @@ mod tests { use super::*; #[test] #[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"] - fn banner_particle_and_breaking_use_exported_models() -> crate::Result<()> { + fn entity_block_particles_and_breaking_use_exported_models() -> crate::Result<()> { use crate::{models::catalog::StateModels, sprites::Sprites}; use horizon_world::{DATA_VERSION, chunk::BlockState, nbt::Tag}; let root = std::path::PathBuf::from( std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), ); - let names = ["white_banner", "white_wall_banner"]; + let names = [ + "white_banner", + "white_wall_banner", + "chest", + "trapped_chest", + "ender_chest", + "copper_chest", + ]; let mut facts: std::collections::BTreeMap = serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?; let states = names.map(|name| { let name = format!("minecraft:{name}"); - let first = facts[&name]["states"][0].clone(); + let mut first = facts[&name]["states"][0].clone(); + if first.get("type").is_some() { + first["type"] = serde_json::json!("single"); + } facts.get_mut(&name).unwrap()["states"] = serde_json::json!([first.clone()]); BlockState { name, @@ -1743,24 +1747,28 @@ mod tests { ("states", Tag::List(states.into())), ( "defaults", - Tag::compound([ - ("minecraft:white_banner", Tag::Int(0)), - ("minecraft:white_wall_banner", Tag::Int(1)), - ]), + Tag::compound(names.iter().enumerate().map(|(id, name)| { + ( + horizon_world::nbt::JavaString::from(format!("minecraft:{name}").as_str()), + Tag::Int(id as i32), + ) + })), ), ]))?; let mut sprites = Sprites::default(); let catalog = StateModels::from_facts(&root, ®istry, &names, &mut sprites, &facts)?; - for id in 0..2 { + for (id, name) in names.iter().enumerate() { let models = catalog.collect( - BlockStateId(id), + BlockStateId(id as u32), horizon_core::position::BlockPos::default(), )?; assert!(models.iter().all(|(_, model)| model.faces.is_empty())); - assert_eq!( - models[0].1.particle, - Some(sprites.layers["minecraft:block/oak_planks"]) - ); + let particle = match *name { + "ender_chest" => "minecraft:block/obsidian", + "copper_chest" => "minecraft:block/copper_block", + _ => "minecraft:block/oak_planks", + }; + assert_eq!(models[0].1.particle, Some(sprites.layers[particle])); } let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?; let renderer = BlockEntityRenderer::new( @@ -1771,17 +1779,28 @@ mod tests { ®istry, ); let world = World::new(BlockStateId(0), 1); - let base_sprites = HashMap::from([( - "entity/banner/banner_base".to_owned(), - Rect { - u0: 0.0, - v0: 0.0, - u1: 1.0, - v1: 1.0, - w: 16, - h: 16, - }, - )]); + let base_sprites = [ + "entity/banner/banner_base", + "entity/chest/normal", + "entity/chest/trapped", + "entity/chest/ender", + "entity/chest/copper", + ] + .into_iter() + .map(|name| { + ( + name.to_owned(), + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }, + ) + }) + .collect(); let mut scene = Scene { camera: DVec3::ZERO, orientation: Quat::IDENTITY, @@ -1798,11 +1817,11 @@ mod tests { banner: &|_| Vec::new(), glyph: &|_| (None, 0.0), }; - for state in 0..2 { + for state in 0..names.len() as u32 { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); let mut cracks = Vec::new(); - renderer.render_banner_breaking(&scene, [0; 3], state, &mut cracks); + renderer.render_breaking(&scene, [0; 3], state, &mut cracks); assert!(!cracks.is_empty()); assert_eq!( base.iter().map(|v| v.pos).collect::>(), @@ -1812,10 +1831,14 @@ mod tests { && v.color == u32::MAX && v.uv.iter().all(|u| u.is_finite()))); scene.game_time = 20; + if state >= 2 { + scene.lid = &|_| 1.0; + } let mut animated = Vec::new(); - renderer.render_banner_breaking(&scene, [0; 3], state, &mut animated); + renderer.render_breaking(&scene, [0; 3], state, &mut animated); assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); scene.game_time = 0; + scene.lid = &|_| 0.0; } Ok(()) } diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index a1e18076e..5e6a3336a 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -301,6 +301,20 @@ pub struct Experience { pub total: i32, } impl Experience { + /// `Player.getBaseExperienceReward`: keep-inventory and spectators drop none. + pub fn death_reward(&self, keep: bool) -> u32 { + if keep { + 0 + } else { + self.level.wrapping_mul(7).clamp(0, 100) as u32 + } + } + /// `ServerPlayer.restoreFrom`: only keep-inventory and spectators retain XP. + pub fn respawn(&mut self, keep: bool) { + if !keep { + *self = Self::default(); + } + } pub fn needed(level: i32) -> i32 { if level >= 30 { 112 + (level - 30) * 9 @@ -540,6 +554,37 @@ impl ArmorStand { } } +#[cfg(test)] +mod experience_tests { + use super::*; + + #[test] + fn death_reward_uses_levels_and_caps_the_recoverable_points() { + for (level, reward) in [(0, 0), (1, 7), (14, 98), (15, 100), (30, 100)] { + let xp = Experience { + level, + progress: 0.75, + total: 10_000, + }; + assert_eq!(xp.death_reward(false), reward); + assert_eq!(xp.death_reward(true), 0); + } + } + + #[test] + fn respawn_clears_all_xp_unless_it_is_kept() { + let mut xp = Experience::default(); + xp.give(155); + let before = (xp.level, xp.progress, xp.total); + xp.respawn(true); + assert_eq!((xp.level, xp.progress, xp.total), before); + xp.respawn(false); + assert_eq!((xp.level, xp.progress, xp.total), (0, 0.0, 0)); + xp.give(7); + assert_eq!((xp.level, xp.progress, xp.total), (1, 0.0, 7)); + } +} + #[cfg(test)] mod fire_environment_tests { use super::*; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d12f43a25..43b2ece7d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3420,11 +3420,8 @@ impl Game<'_> { } if player.health.dead_or_dying() && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. - let at = [ - player.position.x, - player.position.y + 1.32, - player.position.z, - ]; + let feet = [player.position.x, player.position.y, player.position.z]; + let at = [feet[0], feet[1] + 1.32, feet[2]]; let killer = self.combat_killer_kind(); self.death_message(); // ServerPlayer.die: deaths, and the time-since counters restart. @@ -3440,6 +3437,10 @@ impl Game<'_> { } self.stats.reset("custom", "minecraft:time_since_death"); self.stats.reset("custom", "minecraft:time_since_rest"); + let reward = self + .experience + .death_reward(self.ui.rules.bool("keep_inventory") || self.spectator()); + self.spawn_orbs(feet, reward); if !self.creative && !self.ui.rules.bool("keep_inventory") { // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). let mut stacks: Vec = @@ -5616,7 +5617,7 @@ impl Game<'_> { .block(mining.pos[0], mining.pos[1], mining.pos[2]); self.res .block_entity_render - .render_banner_breaking(&scene, mining.pos, state.0, &mut out); + .render_breaking(&scene, mining.pos, state.0, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 1d00134e4..f6fc1e860 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -684,6 +684,8 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; + // What the tick sends a guest goes to its connection at the end. + let holding = lan::Holding::start(); let state = self.lan_host_state(&host); // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { @@ -783,6 +785,10 @@ impl Game<'_> { self.lan_swings(&mut host); self.lan_update_streaming(&host); self.lan_update_models(&mut host); + drop(holding); + for g in &host.hub.guests { + g.sender.flush(); + } self.lan = Some(host); } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ec4ac6cee..af7ff10f8 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -822,6 +822,13 @@ impl Game<'_> { g.saturation = 5.0; g.sent_health = None; g.motion = None; + let mut xp = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + }; + xp.respawn(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); + (g.xp_level, g.xp_progress, g.xp_total) = (xp.level, xp.progress, xp.total); // A new body: nothing given to the old one carries over. if let Some(play) = host.play.get_mut(&conn) { play.potions = Default::default(); @@ -898,6 +905,12 @@ impl Game<'_> { g.dead = true; g.last_death = Some(g.position.map(|v| v.floor() as i32)); let (id, at) = (g.entity_id, g.position); + let reward = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + } + .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); let message = literal(&format!("{} died", g.name)); host.hub.send_to( conn, @@ -905,6 +918,7 @@ impl Game<'_> { ); // LivingEntity.die: the death animation, the dying player included. host.hub.entity_event(id, 3, at); + self.spawn_orbs(at, reward); } } } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 16297e930..ff1f602a4 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -737,10 +737,7 @@ mod tab_list_tests { name: name.into(), info: ClientInformation::new(8), brand: "test".into(), - sender: PlayerSender { - tx, - pending: Arc::default(), - }, + sender: PlayerSender::new(tx, Arc::default()), latency: Arc::new(AtomicI32::new(42)), address: "127.0.0.1:25565".parse().unwrap(), }, diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 54012ca03..3c6f90099 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -260,6 +260,10 @@ impl Game<'_> { .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); + if hit == Some(0) && self.remote.is_none() { + let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); + self.experience.respawn(keep); + } match hit { Some(0) if self.remote.is_some() => { self.ui.death_text = None; diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index a1ffac4fa..fa31f2275 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -21,9 +21,10 @@ use horizon_protocol::{ text::translatable, }; use std::{ + cell::Cell, net::TcpStream, sync::{ - Arc, + Arc, Mutex, PoisonError, atomic::{AtomicI32, AtomicI64, AtomicUsize, Ordering}, mpsc::{Receiver, RecvTimeoutError, Sender, channel}, }, @@ -122,16 +123,64 @@ pub fn valid_name(name: &str) -> bool { (1..=16).contains(&name.len()) && name.chars().all(|c| c as u32 > 32 && (c as u32) < 127) } +thread_local! { + static HOLDING: Cell = const { Cell::new(false) }; +} + +/// While one is alive, the packets this thread sends to each player are held +/// and handed to the player's writer thread together by +/// [`PlayerSender::flush`]: one wake-up per player per tick rather than one +/// per packet. The bytes and their order don't change. +pub struct Holding(bool); +impl Holding { + pub fn start() -> Self { + Self(HOLDING.replace(true)) + } +} +impl Drop for Holding { + fn drop(&mut self) { + HOLDING.set(self.0); + } +} + /// The sending half given to the game thread. #[derive(Clone)] pub struct PlayerSender { pub tx: Sender, pub pending: Arc, + held: Arc>>>, } impl PlayerSender { + pub fn new(tx: Sender, pending: Arc) -> Self { + Self { + tx, + pending, + held: Arc::default(), + } + } + fn held(&self) -> std::sync::MutexGuard<'_, Vec>> { + self.held.lock().unwrap_or_else(PoisonError::into_inner) + } pub fn send(&self, body: Vec) { self.pending.fetch_add(body.len(), Ordering::Relaxed); - let _ = self.tx.send(Out::Packet(body)); + if HOLDING.get() { + self.held().push(body); + } else { + self.flush(); + let _ = self.tx.send(Out::Packet(body)); + } + } + /// Hand the held packets to the writer thread. + pub fn flush(&self) { + let held = std::mem::take(&mut *self.held()); + if !held.is_empty() { + let _ = self.tx.send(Out::Packets(held)); + } + } + /// Send a play disconnect with this reason after what was sent before. + pub fn disconnect(&self, reason: horizon_world::nbt::Tag) { + self.flush(); + let _ = self.tx.send(Out::Disconnect(reason)); } } @@ -466,10 +515,7 @@ fn play(c: Connection, shared: &Arc, parts: Parts, address: std::net::So let pending = Arc::new(AtomicUsize::new(0)); let latency = Arc::new(AtomicI32::new(0)); let alive = Arc::new(AtomicI64::new(-1)); - let sender = PlayerSender { - tx: tx.clone(), - pending: pending.clone(), - }; + let sender = PlayerSender::new(tx.clone(), pending.clone()); let writer_thread = { let (alive, latency, pending) = (alive.clone(), latency.clone(), pending.clone()); std::thread::Builder::new() @@ -544,13 +590,18 @@ fn write_loop( let mut sent_at: Option<(i64, Instant)> = None; let mut next = Instant::now() + KEEP_ALIVE_EVERY; loop { + let mut write = |body: Vec| { + pending.fetch_sub(body.len(), Ordering::Relaxed); + writer.send(&body).is_ok() && pending.load(Ordering::Relaxed) <= MAX_PENDING + }; match rx.recv_timeout(Duration::from_millis(200)) { Ok(Out::Packet(body)) => { - pending.fetch_sub(body.len(), Ordering::Relaxed); - if writer.send(&body).is_err() { + if !write(body) { break; } - if pending.load(Ordering::Relaxed) > MAX_PENDING { + } + Ok(Out::Packets(bodies)) => { + if !bodies.into_iter().all(&mut write) { break; } } @@ -594,3 +645,42 @@ fn write_loop( } writer.shutdown(); } + +#[cfg(test)] +mod tests { + use super::*; + + fn bodies(rx: &Receiver) -> Vec>> { + rx.try_iter() + .map(|out| match out { + Out::Packet(body) => vec![body], + Out::Packets(bodies) => bodies, + Out::Disconnect(_) => vec![b"disconnect".to_vec()], + Out::Close => vec![b"close".to_vec()], + }) + .collect() + } + + #[test] + fn held_packets_go_together_and_in_order() { + let (tx, rx) = channel(); + let sender = PlayerSender::new(tx, Arc::default()); + sender.send(vec![1]); + assert_eq!(bodies(&rx), [vec![vec![1]]]); + let holding = Holding::start(); + sender.send(vec![2]); + sender.send(vec![3]); + assert!(bodies(&rx).is_empty()); + drop(holding); + // A packet sent after the tick still follows the held ones. + sender.send(vec![4]); + assert_eq!(bodies(&rx), [vec![vec![2], vec![3]], vec![vec![4]]]); + let holding = Holding::start(); + sender.send(vec![5]); + sender.disconnect(horizon_world::nbt::Tag::Byte(0)); + drop(holding); + sender.flush(); + assert_eq!(bodies(&rx), [vec![vec![5]], vec![b"disconnect".to_vec()]]); + assert_eq!(sender.pending.load(Ordering::Relaxed), 5); + } +} diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index fad9e0e7d..e9255d822 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -389,7 +389,7 @@ impl Hub { /// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect). pub fn kick(&mut self, conn: u32, reason: Tag) { if let Some(g) = self.guest(conn) { - let _ = g.sender.tx.send(super::Out::Disconnect(reason)); + g.sender.disconnect(reason); } } @@ -1655,7 +1655,7 @@ impl Hub { pub fn disconnect_all(&mut self) { let reason = translatable("multiplayer.disconnect.server_shutdown", &[]); for g in &self.guests { - let _ = g.sender.tx.send(super::Out::Disconnect(reason.clone())); + g.sender.disconnect(reason.clone()); } } } diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 7084f20a6..6af4a1fef 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -21,7 +21,7 @@ pub mod playerdata; mod recipes; pub mod tracking; -pub use conn::PlayerSender; +pub use conn::{Holding, PlayerSender}; use horizon_protocol::packets::play; use horizon_protocol::{ GAME_VERSION, PROTOCOL_VERSION, crypto::uuid_string, packets::configuration::ClientInformation, @@ -69,6 +69,8 @@ pub struct Joined { pub enum Out { /// A packet body: VarInt id and payload. Packet(Vec), + /// Packet bodies held during a tick, in order. + Packets(Vec>), /// Send a play disconnect with this component, then close. Disconnect(horizon_world::nbt::Tag), Close, diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index fb9df356f..6e6ce2e11 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -787,6 +787,17 @@ fn steps( install_datagen_reports(root, &reports)?; } + // The registry and command reports, which the game reads next to these + // files when it serves players (a dedicated server, a LAN world): kept + // here too, so this folder works when it is copied or mounted alone. + let reports = run.local.join("datagen").join("out").join("reports"); + for name in ["registries.json", "commands.json"] { + let (from, to) = (reports.join(name), root.join(name)); + if from.is_file() && (!to.exists() || !run.same("server_sha256")) { + copy(&from, &to)?; + } + } + // Biome parameter tables come from the data generator reports above. prepare_worldgen(run)?;