diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index f9ea1262b..ba4c018ab 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -10,7 +10,7 @@ use horizon_client::{ self, Lan, MAX_PLAYERS, NetConfig, chunks::ChunkEncoder, data::SyncData, - entity::EntityState, + entity::{EntityState, States}, hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, @@ -69,6 +69,9 @@ pub(super) struct LanHost { /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). pub commands: Vec, + /// The entities the guests track, described again every tick + /// (`lan_entities`) over last tick's states. + states: lan::entity::States, } /// The player who owns an integrated server's world: a guest whose state is @@ -136,8 +139,7 @@ fn baby_index(kind: &str) -> Option { /// A mob's synched data as ServerEntity sends it (only the values that differ /// from the defaults the client constructs), with vanilla's entry indices: /// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses. -fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { - let mut meta = Vec::new(); +fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) { let kind = m.kind.id.as_str(); if m.fire_ticks > 0 { meta.push((0, serializer::BYTE, Value::Byte(1))); @@ -280,14 +282,16 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { } _ => {} } - meta } /// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand, /// off hand, feet, legs, chest, head, body, saddle). -fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option)> { +fn mob_equipment( + m: &Mob, + hub: &mut Hub, + out: &mut Vec<(u8, Option)>, +) { let e = &m.extra; - let mut out = Vec::new(); let slots = [ (0u8, &e.main_hand), (1, &e.off_hand), @@ -316,7 +320,6 @@ fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option { waypoints: Default::default(), waypoint_dead: Default::default(), commands: Vec::new(), + states: Default::default(), }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -746,71 +750,36 @@ impl Game<'_> { } /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). - fn lan_entities(&self, host_entity: Option, hub: &mut Hub) -> Vec { - let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len()); + fn lan_entities(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { + out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { - let kind = m.kind.id.as_str(); - let meta = mob_meta(m, hub); - let equipment = mob_equipment(m, hub); - let attributes = self.mob_attributes(m); - let (yaw, pitch) = (m.yaw, m.head_pitch); - out.push(EntityState { - id: m.id as i32, - uuid: entity_uuid(m.id), - kind: kind.to_owned(), - position: [m.position.x, m.position.y, m.position.z], - yaw, - pitch, - head_yaw: m.head_yaw, - on_ground: m.on_ground, - velocity: [m.velocity.x, m.velocity.y, m.velocity.z], - data: 0, - meta, - equipment, - attributes, - precise: false, - }); + let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); + e.position = [m.position.x, m.position.y, m.position.z]; + (e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw); + e.on_ground = m.on_ground; + e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; + mob_meta(m, hub, &mut e.meta); + mob_equipment(m, hub, &mut e.equipment); + self.mob_attributes(m, &mut e.attributes); } for d in &self.dropped { let stack = hub.stack(&Some(d.stack.clone())); - out.push(EntityState { - id: d.id as i32, - uuid: entity_uuid(d.id), - kind: "minecraft:item".to_owned(), - position: [d.position.x, d.position.y, d.position.z], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: d.on_ground, - velocity: [d.velocity.x, d.velocity.y, d.velocity.z], - data: 0, - meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], - equipment: Vec::new(), - attributes: Vec::new(), - precise: false, - }); + let e = out.add(d.id as i32, entity_uuid(d.id), "minecraft:item"); + e.position = [d.position.x, d.position.y, d.position.z]; + e.on_ground = d.on_ground; + e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z]; + e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack))); } for o in &self.orbs { - out.push(EntityState { - id: o.id as i32, - uuid: entity_uuid(o.id), - kind: "minecraft:experience_orb".to_owned(), - position: [o.position.x, o.position.y, o.position.z], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: o.on_ground, - velocity: [o.velocity.x, o.velocity.y, o.velocity.z], - data: 0, - // ExperienceOrb.DATA_VALUE. - meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], - equipment: Vec::new(), - attributes: Vec::new(), - precise: false, - }); + let e = out.add(o.id as i32, entity_uuid(o.id), "minecraft:experience_orb"); + e.position = [o.position.x, o.position.y, o.position.z]; + e.on_ground = o.on_ground; + e.velocity = [o.velocity.x, o.velocity.y, o.velocity.z]; + // ExperienceOrb.DATA_VALUE. + e.meta + .push((8, serializer::INT, Value::Int(o.value as i32))); } - self.lan_object_states(host_entity, hub, &mut out); - out + self.lan_object_states(host_entity, hub, out); } /// Run the hub for this tick and apply what the guests did. @@ -832,21 +801,23 @@ impl Game<'_> { // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { let has_guests = !host.hub.guests.is_empty(); - let entities = if has_guests { + let mut states = std::mem::take(&mut host.states); + if has_guests { let host_entity = state.as_ref().map(|s| s.entity_id); self.lan_assign_ids(); self.lan_riding(host_entity, &mut host.hub.riding); - self.lan_entities(host_entity, &mut host.hub) + self.lan_entities(host_entity, &mut host.hub, &mut states); } else { - Vec::new() - }; + states.clear(); + } + let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state.as_ref(), - entities: &entities, + entities, next_entity: &mut self.next_entity, spawn, difficulty: i32::from(self.ui.difficulty), @@ -887,7 +858,7 @@ impl Game<'_> { self.lan_log_event(event); } HostEvent::Joined(conn) => { - self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn); + self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn); if self.options.dedicated.is_some() && let Some(g) = host.hub.guest(conn) { @@ -952,6 +923,7 @@ impl Game<'_> { } } } + host.states = states; } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); @@ -1011,15 +983,15 @@ impl Game<'_> { g.dimension = in_place; } self.load_guest_records(host, conn); - let theirs; + let mut theirs = States::default(); let entities = if elsewhere { if let Err(e) = self.enter_level(Some(host), level) { log::error!("could not open {}: {e}", level.id()); return; } // A dedicated server has no host player. - theirs = self.lan_entities(None, &mut host.hub); - &theirs[..] + self.lan_entities(None, &mut host.hub, &mut theirs); + theirs.as_slice() } else { entities }; diff --git a/crates/horizon-client/src/game/lan_attributes.rs b/crates/horizon-client/src/game/lan_attributes.rs index 72d06c2ef..73942e770 100644 --- a/crates/horizon-client/src/game/lan_attributes.rs +++ b/crates/horizon-client/src/game/lan_attributes.rs @@ -83,17 +83,16 @@ impl Game<'_> { /// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed /// modifier, its effects' modifiers, its equipment's, and what /// `/attribute` changed. - pub(super) fn mob_attributes(&self, m: &Mob) -> Vec { + pub(super) fn mob_attributes(&self, m: &Mob, out: &mut Vec) { let kind = m.kind.id.as_str(); - let mut out = Vec::new(); if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") { - instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed)); + instance(out, a, finalize::base_value(m, Attr::MovementSpeed)); } if let Some(s) = m.extra.attributes.as_deref() { for (attr, v) in &s.bases { if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name())) { - instance(&mut out, a, *v).base = *v; + instance(out, a, *v).base = *v; } } for x in &s.modifiers { @@ -101,7 +100,7 @@ impl Game<'_> { self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name())) { add_modifier( - &mut out, + out, a, finalize::base_value(m, x.attr), AttributeModifier { @@ -122,7 +121,7 @@ impl Game<'_> { finalize::transient(m, Attr::MovementSpeed), ) { add_modifier( - &mut out, + out, a, finalize::base_value(m, Attr::MovementSpeed), AttributeModifier { @@ -150,7 +149,7 @@ impl Game<'_> { }; let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute)); add_modifier( - &mut out, + out, a, start, AttributeModifier { @@ -172,10 +171,9 @@ impl Game<'_> { ("chest", e.chest.as_ref()), ("head", e.head.as_ref()), ], - &mut out, + out, ); - self.generic_attributes_of(Target::Mob(m.id), &mut out); - out + self.generic_attributes_of(Target::Mob(m.id), out); } /// An armor stand's synced instances: movement speed (its first diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 7230e323d..404d00c46 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -5,7 +5,7 @@ //! synched data that differs from the defaults), and who rides what. use super::Game; use horizon_client::lan::{ - entity::{EntityState, Riding}, + entity::{EntityState, Riding, States}, hub::Hub, }; use horizon_protocol::entity_data::{Value, serializer}; @@ -107,7 +107,7 @@ impl Game<'_> { &self, host_entity: Option, hub: &mut Hub, - out: &mut Vec, + out: &mut States, ) { for b in &self.boats { let p = b.position; @@ -268,12 +268,7 @@ impl Game<'_> { /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and /// end crystals, as guests track them. - fn lan_projectile_states( - &self, - host_entity: Option, - hub: &mut Hub, - out: &mut Vec, - ) { + fn lan_projectile_states(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { let owner = |who: Option| match who { Some(horizon_client::mobs::Who::Mob(id)) => id as i32, Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0), diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index c1156001c..c4e8052c0 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -34,7 +34,7 @@ pub fn changed_attributes( } /// What the game says about one entity this tick. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct EntityState { pub id: i32, pub uuid: u128, @@ -61,6 +61,72 @@ pub struct EntityState { pub precise: bool, } +impl EntityState { + /// The entity `id` of type `kind` as a fresh state has it: at the origin, + /// at rest, with no data, equipment or attributes. Keeps the allocations + /// of the strings and vectors it held. + pub fn reset(&mut self, id: i32, uuid: u128, kind: &str) { + self.id = id; + self.uuid = uuid; + self.kind.clear(); + self.kind.push_str(kind); + self.position = [0.0; 3]; + (self.yaw, self.pitch, self.head_yaw) = (0.0, 0.0, 0.0); + self.on_ground = false; + self.velocity = [0.0; 3]; + self.data = 0; + self.meta.clear(); + self.equipment.clear(); + self.attributes.clear(); + self.precise = false; + } +} + +/// The states a level describes its entities with, kept from tick to tick: +/// each tick's are written over the last tick's in place, so the strings and +/// vectors in them are reused instead of being made and freed again for every +/// entity on every tick. +#[derive(Default)] +pub struct States { + list: Vec, + len: usize, +} + +impl States { + /// Start a new tick's states. + pub fn clear(&mut self) { + self.len = 0; + } + /// The next entity's state, reset (`EntityState::reset`). + pub fn add(&mut self, id: i32, uuid: u128, kind: &str) -> &mut EntityState { + if self.len == self.list.len() { + self.list.push(EntityState::default()); + } + let e = &mut self.list[self.len]; + self.len += 1; + e.reset(id, uuid, kind); + e + } + pub fn push(&mut self, e: EntityState) { + match self.list.get_mut(self.len) { + Some(slot) => *slot = e, + None => self.list.push(e), + } + self.len += 1; + } + pub fn as_slice(&self) -> &[EntityState] { + &self.list[..self.len] + } +} + +impl Extend for States { + fn extend>(&mut self, states: I) { + for e in states { + self.push(e); + } + } +} + /// `AbstractArrow`: every update sends its position and rotation. fn is_arrow(kind: &str) -> bool { matches!( @@ -792,6 +858,31 @@ mod tests { } } + #[test] + fn states_are_written_over_last_ticks_in_place() { + let mut states = States::default(); + let e = states.add(1, 1, "minecraft:zombie"); + e.position = [1.0, 2.0, 3.0]; + e.meta.push((9, serializer::FLOAT, Value::Float(20.0))); + e.equipment.push((0, None)); + let (kind, meta) = (e.kind.as_ptr(), e.meta.as_ptr()); + states.push(state(2.0)); + states.clear(); + let e = states.add(3, 3, "minecraft:husk"); + // Nothing of the last tick's state is left, but its allocations are. + let fresh = EntityState { + id: 3, + uuid: 3, + kind: "minecraft:husk".into(), + ..EntityState::default() + }; + assert_eq!(*e, fresh); + assert_eq!((e.kind.as_ptr(), e.meta.as_ptr()), (kind, meta)); + assert_eq!(states.as_slice(), std::slice::from_ref(&fresh)); + states.extend([state(5.0), state(6.0)]); + assert_eq!(states.as_slice(), [fresh, state(5.0), state(6.0)]); + } + /// The entity as added this tick, then its updates (one a tick). fn added(e: &EntityState) -> ServerEntity { ServerEntity::new(e, Some(100), &Riding::default())