From f5a795988ba683a1919fa598cd6d504e65b37a6f Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:56:59 -0400 Subject: [PATCH 001/327] Draw sulfur cube cores before translucent shells --- crates/horizon-client/src/mobs/render.rs | 120 ++++++++++++++++++++--- 1 file changed, 109 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index a3b29f63b..e36879c02 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1023,17 +1023,24 @@ fn render_visible( .unwrap_or_else(|| m.kind.model.clone()); let mut poses = Poses::new(&model); anim::setup(m, &s, &mut poses, &data.animations); - if let Some(uv) = atlas(&texture) { - draw( - &model, - base, - &poses, - uv, - body_color(m, alpha), - light, - body_overlay(m, alpha), - out, - ); + let draw_body = |out: &mut Vec| { + if let Some(uv) = atlas(&texture) { + draw( + &model, + base, + &poses, + uv, + body_color(m, alpha), + light, + body_overlay(m, alpha), + out, + ); + } + }; + // The translucent shell writes depth: draw the opaque core before it. + let shell_last = m.species() == Species::SulfurCube; + if !shell_last { + draw_body(out); } for (part, uv, color) in extra { draw(part, base, &poses, *uv, *color, light, overlay, out); @@ -1081,6 +1088,9 @@ fn render_visible( } } } + if shell_last { + draw_body(out); + } } /// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`). fn armor_slot(model: &str) -> Option { @@ -1221,3 +1231,91 @@ pub fn held_item_transform( anim::setup(m, &s, &mut poses, &data.animations); hand_base(m, &model, base, &poses, left) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sulfur_cube_opaque_core_is_submitted_before_its_translucent_shell() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("entity-models.json").exists() { + return; + } + let mut types = super::super::MobTypes::load(&root).unwrap(); + let kind = std::sync::Arc::new(types.types.remove("minecraft:sulfur_cube").unwrap()); + let data = MobData { + states: Vec::new(), + placements: Default::default(), + heightmaps: Default::default(), + animations: Default::default(), + biome_tags: Default::default(), + entity_tags: Default::default(), + }; + let atlas = |name: &str| { + Some(if name.contains("_inner") { + [0.0, 0.0, 0.25, 0.25] + } else { + [0.5, 0.5, 0.75, 0.75] + }) + }; + for baby in [false, true] { + let mut mob = Mob::new(1, kind.clone(), horizon_core::geometry::Vec3::ZERO, 0.0); + mob.extra.age = if baby { -24000 } else { 0 }; + super::super::sulfur_cube::finalize(&mut mob); + assert_eq!(mob.is_baby(), baby); + for posed in [false, true] { + let mut vertices = Vec::new(); + if posed { + render_posed( + &mob, + 0.5, + glam::Mat4::IDENTITY, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + } else { + render( + &mob, + 0.5, + glam::DVec3::ZERO, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + } + assert_eq!( + vertices.len(), + 48, + "both real six-face models must be drawn" + ); + assert!( + vertices[..24].iter().all(|v| v.uv[0] <= 0.25), + "opaque core must precede shell" + ); + assert!(vertices[24..].iter().all(|v| v.uv[0] >= 0.5)); + } + mob.extra.head = Some("minecraft:stone".into()); + let mut vertices = Vec::new(); + render( + &mob, + 0.5, + glam::DVec3::ZERO, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + assert_eq!( + vertices.len(), + 24, + "a swallowed block still hides the default core" + ); + assert!(vertices.iter().all(|v| v.uv[0] >= 0.5)); + } + } +} From 18e9c1464275ef54e3d2667897e57726e1985838 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:12:08 -0400 Subject: [PATCH 002/327] Render swallowed sulfur cube blocks and award Uh Oh --- crates/horizon-client/src/advancements.rs | 93 ++++++++++++- crates/horizon-client/src/entities.rs | 2 + crates/horizon-client/src/entity_nbt.rs | 14 +- crates/horizon-client/src/game.rs | 5 + .../horizon-client/src/game/advancements.rs | 13 ++ crates/horizon-client/src/game/creatures.rs | 14 ++ crates/horizon-client/src/game/remote.rs | 1 + crates/horizon-client/src/game/spawner.rs | 8 ++ .../horizon-client/src/game/sulfur_cubes.rs | 130 +++++++++++++++++- crates/horizon-client/src/save.rs | 24 ++-- 10 files changed, 290 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 4a2666ded..11092018c 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -560,6 +560,29 @@ pub struct Entities<'a> { pub tool: Option<&'a ItemView>, pub block_pos: Option<[i32; 3]>, } +/// Conditions shared by item/entity interactions and thrown-item pickups. +pub fn item_entity( + v: &Value, + player: &EntityView, + target: &EntityView, + stack: &ItemView, + w: &dyn World, +) -> bool { + let pctx = Entities { + this: Some(player), + origin: player.position, + tool: None, + block_pos: None, + }; + let ectx = Entities { + this: Some(target), + ..pctx + }; + conditions(&v["player"], &pctx, w) + && conditions(&v["entity"], &ectx, w) + && item(&v["item"], stack, w) +} + /// A `ContextAwarePredicate`: a list of loot conditions (or one condition). pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool { match v { @@ -949,7 +972,75 @@ mod tests { false } fn in_tag(&self, _: &str, tag: &str, id: &str) -> bool { - tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone" + (tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone") + || (tag == "minecraft:sulfur_cube_archetype/explosive" && id == "minecraft:tnt") + } + } + #[test] + fn uh_oh_accepts_either_tnt_event_only_for_adult_sulfur_cubes() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join( + "../../.local/horizon-client/26.3/data/minecraft/advancement/husbandry/uh_oh.json", + ); + if !path.exists() { + return; + } + let json = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let advancement = parse("minecraft:husbandry/uh_oh", &json).unwrap(); + assert_eq!(advancement.criteria.len(), 2); + let player = EntityView { + kind: "minecraft:player".into(), + ..Default::default() + }; + let mut target = EntityView { + kind: "minecraft:sulfur_cube".into(), + ..Default::default() + }; + let mut stack = ItemView { + id: "minecraft:tnt".into(), + count: 1, + ..Default::default() + }; + for criterion in &advancement.criteria { + assert!(item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + let mut progress = Progress::default(); + progress.grant(&advancement.id, &criterion.name, "test"); + assert!( + progress.done(&advancement), + "either criterion must award Uh Oh" + ); + target.baby = true; + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + target.baby = false; + target.kind = "minecraft:pig".into(); + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + target.kind = "minecraft:sulfur_cube".into(); + stack.id = "minecraft:stone".into(); + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + stack.id = "minecraft:tnt".into(); } } #[test] diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index a1e18076e..d0a773ccf 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -16,6 +16,7 @@ pub struct ItemEntity { pub fire_ticks: i32, pub id: u32, pub stack: ItemStack, + pub thrower: Option<[i32; 4]>, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -565,6 +566,7 @@ mod fire_environment_tests { .unwrap(); let make = |id: &str| ItemEntity { id: 1, + thrower: None, stack: ItemStack { item: std::sync::Arc::from(id), count: 1, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 11601db78..eefce5ee2 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -858,7 +858,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - Some(m) } -/// `ItemEntity`: Health, Age, PickupDelay, Item. +/// `ItemEntity`: Health, Age, PickupDelay, Item, Thrower. pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let base = Base { id: "minecraft:item", @@ -882,6 +882,11 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> ] { put(&mut tag, key, value); } + if let Some(thrower) = e.thrower { + put(&mut tag, "Thrower", Tag::IntArray(thrower.to_vec())); + } else if let Tag::Compound(map) = &mut tag { + map.remove(&"Thrower".into()); + } tag } pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { @@ -892,6 +897,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { self.dropped.push(ItemEntity { health: 5, fire_ticks: 0, + thrower: None, id: self.next_entity, stack, position: p, @@ -1450,6 +1451,10 @@ impl Game<'_> { yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, ]; self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); + if self.lan_acting.is_none() { + let uuid = self.level.ensure_player_uuid(); + self.dropped.last_mut().unwrap().thrower = Some(uuid); + } } fn tick_items(&mut self) { let mut items = std::mem::take(&mut self.dropped); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 4c5c0fbbe..4d51ce5e4 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -655,6 +655,19 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w) }); } + pub(super) fn trigger_item_entity( + &mut self, + name: &str, + stack: &ItemStack, + target: &EntityView, + ) { + if self.lan_acting.is_some() { + return; + } + let me = self.player_entity(); + let it = item_view(stack); + self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); + } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { let Some(definition) = self.res.assets.registry.state(state).cloned() else { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index aea114d30..28c6f0996 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2183,6 +2183,10 @@ impl Game<'_> { return Ok(true); } if self.interact_sulfur_cube(index, &item) { + if let Some(stack) = &held { + let target = self.mob_entity(&self.mobs[index]); + self.trigger_item_entity("minecraft:player_interacted_with_entity", stack, &target); + } self.swing_arm(); return Ok(true); } @@ -2731,6 +2735,16 @@ impl Game<'_> { if mob.fire_ticks > 0 || matches!(mob.species(), Species::Blaze | Species::MagmaCube) { packed = (15 * 16) | ((15 * 16) << 8); } + if mob.species() == Species::SulfurCube + && !horizon_client::mobs::trader::is_invisible(mob) + { + self.sulfur_cube_body_geometry( + mob, + horizon_client::mobs::render::base_transform(mob, alpha as f32, camera), + packed, + out, + ); + } horizon_client::mobs::render::render( mob, alpha as f32, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f527f3ea6..ddef62cbb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1581,6 +1581,7 @@ impl Game<'_> { self.dropped.push(ItemEntity { health: 5, fire_ticks: 0, + thrower: None, id: id as u32, stack, position: at, diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 30b8cc67b..0f9685e9b 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -410,6 +410,14 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::splat(scale)); let light = self.world.light(key.0, key.1, key.2); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + if mob.species() == horizon_client::mobs::Species::SulfurCube { + self.sulfur_cube_body_geometry( + mob, + horizon_client::mobs::render::base_transform_at(mob, alpha as f32, origin), + packed, + out, + ); + } horizon_client::mobs::render::render_posed( mob, alpha as f32, diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 4606f6859..6b3cc1b21 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -5,11 +5,50 @@ use super::Game; use horizon_client::{ items::ItemStack, + mesher::Vertex, mobs::{Mob, Species, sulfur_cube}, }; -use horizon_core::random::RandomSource; +use horizon_core::{position::BlockPos, random::RandomSource}; + +fn block_transform(base: glam::Mat4) -> glam::Mat4 { + base * glam::Mat4::from_scale(glam::Vec3::new(1.0, -1.0, -1.0)) + * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)) +} impl Game<'_> { + /// The swallowed block replaces the opaque core and precedes the shell. + pub(super) fn sulfur_cube_body_geometry( + &self, + mob: &Mob, + base: glam::Mat4, + light: u32, + out: &mut Vec, + ) { + let Some(state) = mob + .extra + .head + .as_deref() + .and_then(|item| self.res.items.get(item)) + .and_then(|item| item.block) + else { + return; + }; + let start = out.len(); + self.block_model_vertices( + state, + BlockPos::default(), + block_transform(base), + light, + out, + ); + let overlay = horizon_client::overlay::living(0.0, mob.hurt_time > 0 || mob.death_time > 0); + if overlay != 0 { + for vertex in &mut out[start..] { + vertex.layer = overlay; + } + } + } + fn sulfur_sound(&mut self, index: usize, sound: &str) { let at = self.mobs[index].center(); self.audio @@ -126,6 +165,11 @@ impl Game<'_> { continue; } let item = e.stack.item.clone(); + let thrown_by_player = e + .thrower + .is_some_and(|uuid| Some(uuid) == self.level.player_uuid); + let mut swallowed = e.stack.clone(); + swallowed.count = 1; let (taken_item, id) = (e.clone(), self.mobs[i].id); self.add_pickup( super::pickups::Taken::Item(Box::new(taken_item)), @@ -140,6 +184,14 @@ impl Game<'_> { m.extra.head = Some(item); m.extra.point = None; self.sulfur_sound(i, "entity.sulfur_cube.absorb"); + if thrown_by_player { + let target = self.mob_entity(&self.mobs[i]); + self.trigger_item_entity( + "minecraft:thrown_item_picked_up_by_entity", + &swallowed, + &target, + ); + } } } /// `AbstractCubeMob.remove`: a dead adult splits into two babies (none @@ -167,3 +219,79 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn swallowed_block_occupies_the_default_cores_volume() { + use horizon_client::mobs::{EntityModelDocument, anim::Poses, render}; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("entity-models.json").exists() { + return; + } + let model = EntityModelDocument::load(&root) + .unwrap() + .model("minecraft:sulfur_cube#inner") + .unwrap(); + let base = glam::Mat4::from_translation(glam::Vec3::new(3.0, 4.0, -2.0)) + * glam::Mat4::from_rotation_y(0.7) + * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + let mut core = Vec::new(); + render::draw( + &model, + base, + &Poses::new(&model), + [0.0; 4], + u32::MAX, + 0, + 0, + &mut core, + ); + let block = block_transform(base); + let corners: Vec<_> = (0..8) + .map(|i| { + block.transform_point3(glam::Vec3::new( + (i & 1) as f32, + ((i >> 1) & 1) as f32, + ((i >> 2) & 1) as f32, + )) + }) + .collect(); + for axis in 0..3 { + let lo = core + .iter() + .map(|v| v.pos[axis]) + .fold(f32::INFINITY, f32::min); + let hi = core + .iter() + .map(|v| v.pos[axis]) + .fold(f32::NEG_INFINITY, f32::max); + assert!( + (corners + .iter() + .map(|p| p[axis]) + .fold(f32::INFINITY, f32::min) + - lo) + .abs() + < 1e-5 + ); + assert!( + (corners + .iter() + .map(|p| p[axis]) + .fold(f32::NEG_INFINITY, f32::max) + - hi) + .abs() + < 1e-5 + ); + } + let up = block.transform_vector3(glam::Vec3::Y); + assert!( + up.y > 0.0, + "block textures must stay upright inside the model" + ); + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 9660d237e..b5778f40d 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2124,6 +2124,18 @@ pub struct Level { pub player_extra: Option, } impl Level { + /// Initialize the offline single-player identity before saving or dropping items. + pub fn ensure_player_uuid(&mut self) -> [i32; 4] { + *self.player_uuid.get_or_insert_with(|| { + let u = horizon_protocol::crypto::offline_uuid("Player"); + [ + (u >> 96) as u32 as i32, + (u >> 64) as u32 as i32, + (u >> 32) as u32 as i32, + u as u32 as i32, + ] + }) + } pub fn game_rule(&self, name: &str) -> i32 { self.game_rules .get(name) @@ -2578,17 +2590,7 @@ impl Level { map.remove(&JavaString::from(key)); } } - // A new world's player has the offline profile id of its name - // (UUIDUtil.createOfflinePlayerUUID), as in an offline single-player game. - let uuid = *self.player_uuid.get_or_insert_with(|| { - let u = horizon_protocol::crypto::offline_uuid("Player"); - [ - (u >> 96) as u32 as i32, - (u >> 64) as u32 as i32, - (u >> 32) as u32 as i32, - u as u32 as i32, - ] - }); + let uuid = self.ensure_player_uuid(); // A new world's first spawn point is its world spawn. if self.world_spawn.is_none() { self.world_spawn = self.spawn.map(|s| { From e43e8ae82b147e683ba9067a2acb0aa0705169f2 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:19:39 -0400 Subject: [PATCH 003/327] Match sulfur cube block placement, lighting and fuse flashes --- crates/horizon-client/src/game.rs | 3 +- .../horizon-client/src/game/armor_stands.rs | 2 +- crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/minecarts.rs | 32 +++- crates/horizon-client/src/game/spawner.rs | 1 + .../horizon-client/src/game/sulfur_cubes.rs | 148 +++++++++--------- crates/horizon-client/src/models/catalog.rs | 12 +- 7 files changed, 109 insertions(+), 90 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 03d0ab497..504cc4682 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5564,9 +5564,10 @@ impl Game<'_> { let start = out.len(); self.block_model_vertices( f.state, - f.start_pos, + horizon_core::random::position_seed(f.start_pos), glam::Mat4::from_translation(o), packed, + false, &mut out, ); let tint = horizon_client::mobs::render::abgr(tint); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 78eb22330..df85b9e62 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -693,7 +693,7 @@ impl Game<'_> { } } /// `AbstractSkullBlock.getType` of a skull item. -fn skull_kind(item: &str) -> Option<&'static str> { +pub(super) fn skull_kind(item: &str) -> Option<&'static str> { Some(match item { "minecraft:skeleton_skull" => "skeleton", "minecraft:wither_skeleton_skull" => "wither_skeleton", diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 28c6f0996..8c7baa5b8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2740,6 +2740,7 @@ impl Game<'_> { { self.sulfur_cube_body_geometry( mob, + alpha as f32, horizon_client::mobs::render::base_transform(mob, alpha as f32, camera), packed, out, diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 06d5466da..fd10b4562 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -17,7 +17,6 @@ use horizon_client::{ }; use horizon_core::{ geometry::{Aabb, Vec3}, - position::BlockPos, random::RandomSource, }; use horizon_world::registry::BlockStateId; @@ -1139,16 +1138,17 @@ impl Game<'_> { } } } - /// A block model's faces under `m` (block space 0..1), lit flat. + /// Baked block faces with terrain shade or block-item diffuse lighting. pub(super) fn block_model_vertices( &self, state: BlockStateId, - seed_pos: BlockPos, + seed: i64, m: glam::Mat4, light: u32, + diffuse: bool, out: &mut Vec, ) { - let Ok(models) = self.res.assets.model_catalog.collect(state, seed_pos) else { + let Ok(models) = self.res.assets.model_catalog.collect_seeded(state, seed) else { return; }; for (_, model) in &models { @@ -1168,12 +1168,30 @@ impl Game<'_> { D::North | D::South => 204, D::West | D::East => 153, }; - let color = 0xFF00_0000 | shade << 16 | shade << 8 | shade; + let color = if diffuse { + u32::MAX + } else { + 0xFF00_0000 | shade << 16 | shade << 8 | shade + }; + let normal = if diffuse { + use horizon_client::item_render::{direction_vector, transform_normal}; + let n = transform_normal(m, direction_vector(face.quad.facing)); + let n = n.to_array().map(|v| (v.clamp(-1.0, 1.0) * 127.0) as i8); + [n[0], n[1], n[2], 127] + } else { + [0; 4] + }; + let light = if diffuse { + let emission = u32::from(face.quad.light_emission) * 16; + (light & 0xFF) | (light >> 8 & 0xFF).max(emission) << 8 + } else { + light + }; for k in 0..4 { let p = face.quad.positions[k]; let uv = face.quad.uv[k]; out.push(Vertex { - normal: [0; 4], + normal, pos: m.transform_point3(glam::Vec3::from_array(p)).to_array(), uv: [s.u0 + uv[0] * (s.u1 - s.u0), s.v0 + uv[1] * (s.v1 - s.v0)], layer: 0, @@ -1297,7 +1315,7 @@ impl Game<'_> { * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0; let start = out.len(); - self.block_model_vertices(state, BlockPos::default(), m, packed, out); + self.block_model_vertices(state, 0, m, packed, false, out); if flash { // submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light. for v in &mut out[start..] { diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 0f9685e9b..1563d9459 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -413,6 +413,7 @@ impl Game<'_> { if mob.species() == horizon_client::mobs::Species::SulfurCube { self.sulfur_cube_body_geometry( mob, + alpha as f32, horizon_client::mobs::render::base_transform_at(mob, alpha as f32, origin), packed, out, diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 6b3cc1b21..59c5f9ed0 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -8,11 +8,30 @@ use horizon_client::{ mesher::Vertex, mobs::{Mob, Species, sulfur_cube}, }; -use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_core::random::RandomSource; -fn block_transform(base: glam::Mat4) -> glam::Mat4 { +fn block_transform(base: glam::Mat4, baby: bool) -> glam::Mat4 { base * glam::Mat4::from_scale(glam::Vec3::new(1.0, -1.0, -1.0)) - * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)) + * glam::Mat4::from_scale(glam::Vec3::splat(if baby { 0.5 } else { 1.0 })) + * glam::Mat4::from_translation(glam::Vec3::new(-0.5, -0.518, -0.5)) +} + +fn block_overlay(fuse_ticks: i32, alpha: f32, hurt: bool) -> u32 { + let fuse = if fuse_ticks >= 0 { + fuse_ticks as f32 - alpha + 1.0 + } else { + 0.0 + }; + if fuse > 0.0 && (fuse / 5.0) as i32 % 2 == 0 { + horizon_client::overlay::living(1.0, false) + } else { + horizon_client::overlay::living(0.0, hurt) + } +} + +fn block_light(light: u32, emission: u8) -> u32 { + let block = (light >> 8 & 0xFF).max(u32::from(emission) * 16); + (light & 0xFF) | block << 8 } impl Game<'_> { @@ -20,28 +39,34 @@ impl Game<'_> { pub(super) fn sulfur_cube_body_geometry( &self, mob: &Mob, + alpha: f32, base: glam::Mat4, light: u32, out: &mut Vec, ) { - let Some(state) = mob - .extra - .head - .as_deref() - .and_then(|item| self.res.items.get(item)) - .and_then(|item| item.block) - else { + let Some(item) = mob.extra.head.as_deref() else { + return; + }; + if super::armor_stands::skull_kind(item).is_some() { + return; + } + let Some(state) = self.res.items.get(item).and_then(|item| item.block) else { return; }; let start = out.len(); self.block_model_vertices( state, - BlockPos::default(), - block_transform(base), - light, + 42, + block_transform(base, mob.is_baby()), + block_light(light, self.res.facts.get(state).emission), + true, out, ); - let overlay = horizon_client::overlay::living(0.0, mob.hurt_time > 0 || mob.death_time > 0); + let overlay = block_overlay( + sulfur_cube::fuse(mob), + alpha, + mob.hurt_time > 0 || mob.death_time > 0, + ); if overlay != 0 { for vertex in &mut out[start..] { vertex.layer = overlay; @@ -225,73 +250,40 @@ mod tests { use super::*; #[test] - fn swallowed_block_occupies_the_default_cores_volume() { - use horizon_client::mobs::{EntityModelDocument, anim::Poses, render}; - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../.local/horizon-client/26.3"); - if !root.join("entity-models.json").exists() { - return; - } - let model = EntityModelDocument::load(&root) - .unwrap() - .model("minecraft:sulfur_cube#inner") - .unwrap(); + fn swallowed_block_uses_vanilla_lift_and_baby_scale() { let base = glam::Mat4::from_translation(glam::Vec3::new(3.0, 4.0, -2.0)) * glam::Mat4::from_rotation_y(0.7) * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); - let mut core = Vec::new(); - render::draw( - &model, - base, - &Poses::new(&model), - [0.0; 4], - u32::MAX, - 0, - 0, - &mut core, - ); - let block = block_transform(base); - let corners: Vec<_> = (0..8) - .map(|i| { - block.transform_point3(glam::Vec3::new( - (i & 1) as f32, - ((i >> 1) & 1) as f32, - ((i >> 2) & 1) as f32, - )) - }) - .collect(); - for axis in 0..3 { - let lo = core - .iter() - .map(|v| v.pos[axis]) - .fold(f32::INFINITY, f32::min); - let hi = core - .iter() - .map(|v| v.pos[axis]) - .fold(f32::NEG_INFINITY, f32::max); - assert!( - (corners - .iter() - .map(|p| p[axis]) - .fold(f32::INFINITY, f32::min) - - lo) - .abs() - < 1e-5 - ); - assert!( - (corners - .iter() - .map(|p| p[axis]) - .fold(f32::NEG_INFINITY, f32::max) - - hi) - .abs() - < 1e-5 - ); + for baby in [false, true] { + let size = if baby { 0.5 } else { 1.0 }; + let block = block_transform(base, baby); + for (point, expected) in [ + (glam::Vec3::ZERO, glam::Vec3::new(-0.5, 0.518, 0.5)), + (glam::Vec3::ONE, glam::Vec3::new(0.5, -0.482, -0.5)), + ] { + let actual = block.transform_point3(point); + let expected = base.transform_point3(expected * size); + assert!(actual.abs_diff_eq(expected, 1e-5), "baby={baby}"); + } + assert!(block.transform_vector3(glam::Vec3::Y).y > 0.0); } - let up = block.transform_vector3(glam::Vec3::Y); - assert!( - up.y > 0.0, - "block textures must stay upright inside the model" - ); + } + + #[test] + fn swallowed_tnt_flashes_white_over_hurt_using_the_interpolated_fuse() { + let white = horizon_client::overlay::WHITE + 15; + assert_eq!(block_overlay(-1, 0.0, false), 0); + assert_eq!(block_overlay(-1, 0.0, true), 1); + assert_eq!(block_overlay(9, 0.0, true), white); + assert_eq!(block_overlay(9, 0.5, false), 0); + assert_eq!(block_overlay(9, 0.5, true), 1); + assert_eq!(block_overlay(0, 0.5, false), white); + } + + #[test] + fn contained_block_emission_preserves_brighter_light_and_the_sky_channel() { + assert_eq!(block_light(0x2050, 1), 0x2050); + assert_eq!(block_light(0x2050, 7), 0x7050); + assert_eq!(block_light(0x0070, 0), 0x0070); } } diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index 59a885821..4b5d36d26 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -222,14 +222,20 @@ impl StateModels { &self, state: BlockStateId, position: BlockPos, + ) -> Result> { + // Blocks use their position seed; contained/displayed blocks can supply one. + self.collect_seeded(state, position_seed(position)) + } + pub fn collect_seeded( + &self, + state: BlockStateId, + seed: i64, ) -> Result> { let (choice, selected) = self .states .get(&state) .ok_or("unbound gallery block state")?; - // These inspection blocks use Block's default position seed. Blocks with - // specialized model seeds (e.g. two-block structures) need their callbacks. - let mut random = LegacyRandom::new(position_seed(position)); + let mut random = LegacyRandom::new(seed); let mut variants = Vec::new(); self.choices[*choice].collect(selected, &mut random, &mut variants)?; variants From 92236010fd4994b3bd9d08f0adb0621d78f733cb Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:22:07 -0400 Subject: [PATCH 004/327] Document the sulfur body component limitation --- crates/horizon-client/src/game/sulfur_cubes.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 59c5f9ed0..c4cee6319 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -50,6 +50,8 @@ impl Game<'_> { if super::armor_stands::skull_kind(item).is_some() { return; } + // shortcut: the body slot retains only an item id; preserve the stack + // before supporting its block-state components here. let Some(state) = self.res.items.get(item).and_then(|item| item.block) else { return; }; From e7003e7d4941709cdd3e2e73eedeb26eb52f63f3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:59:36 +0200 Subject: [PATCH 005/327] Dedicated server: online mode, and refused logins in the log online-mode=true now authenticates players as vanilla's ServerLoginPacketListenerImpl does. The server makes a 1024-bit RSA key pair at startup ("Generating keypair"), sends it with a random challenge, checks the challenge and decrypts the shared secret from the client's key packet, encrypts the connection with AES/CFB8, and asks the session service's verify endpoint (hasJoined, through the services discovery document) whether the player joined with the server's hash, from the "User Authenticator #N" thread. A verified profile keeps its UUID and properties, so skins show in the player list; an unverified one is refused with "Failed to verify username!", and an unreachable service with authservers_down. The offline-mode warnings are only printed in offline mode. Refused logins are logged as vanilla logs them: "Disconnecting (/
): " and " (/
) lost connection: ", with log-ips respected. horizon-protocol gains RSA key generation (Miller-Rabin primes, e = 65537), the X.509 encoding of the public key and PKCS#1 v1.5 decryption. test_online_mode_parity.py runs its logins against Horizon's server too, plus a verified player the whitelist refuses, and compares the two servers' log lines about the player. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/auth.rs | 95 +++++++ crates/horizon-client/src/game/dedicated.rs | 56 ++-- crates/horizon-client/src/game/scoreboard.rs | 1 + crates/horizon-client/src/lan/conn.rs | 187 ++++++++++++- crates/horizon-client/src/lan/guest.rs | 3 + crates/horizon-client/src/lan/hub.rs | 7 +- crates/horizon-client/src/lan/mod.rs | 28 ++ crates/horizon-protocol/src/rsa.rs | 280 ++++++++++++++++++- docs/server.md | 12 +- tools/test_online_mode_parity.py | 108 +++++-- 10 files changed, 713 insertions(+), 64 deletions(-) diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index 27339259f..a6dfab1ee 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -232,6 +232,87 @@ pub fn join_server(session: &AuthSession, server_hash: &str) -> Result<(), JoinE } } +/// What the session service says about a player joining this server +/// (MinecraftServicesSessionService.hasJoinedServer). +#[derive(Clone, Debug, PartialEq)] +pub struct JoinedProfile { + pub uuid: u128, + pub properties: Vec, +} + +/// HttpDiscoveryService.buildQuery: `URLEncoder.encode(value, UTF-8)`. +fn url_encode(text: &str) -> String { + let mut out = String::new(); + for b in text.bytes() { + match b { + b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'-' | b'*' | b'_' => { + out.push(char::from(b)); + } + b' ' => out.push('+'), + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +/// The session service's verify endpoint, asked by an online-mode server +/// whether `name` joined with `server_hash` (and from `ip`, when the server +/// prevents proxy connections). `Ok(None)`: it didn't, or the service said +/// no; `Err(Unavailable)`: no answer. +pub fn has_joined( + name: &str, + server_hash: &str, + ip: Option, +) -> Result, JoinError> { + let doc = discovery()?; + let url = endpoint(&doc, "session", "verify").ok_or(JoinError::Unavailable)?; + let mut query = format!( + "username={}&serverId={}", + url_encode(name), + url_encode(server_hash) + ); + if let Some(ip) = ip { + query.push_str(&format!("&ip={}", url_encode(&ip.to_string()))); + } + let separator = if url.contains('?') { '&' } else { '?' }; + let body = match agent().get(&format!("{url}{separator}{query}")).call() { + Ok(response) => response.into_string().unwrap_or_default(), + Err(ureq::Error::Status(status, response)) => { + let error = + JoinError::from_response(status, &response.into_string().unwrap_or_default()); + return match error { + JoinError::Unavailable => Err(error), + _ => Ok(None), + }; + } + Err(ureq::Error::Transport(_)) => return Err(JoinError::Unavailable), + }; + Ok(parse_joined(&body)) +} + +/// HasJoinedMinecraftServerResponse: `id` and `properties`; no id is no profile. +pub fn parse_joined(body: &str) -> Option { + let v: serde_json::Value = serde_json::from_str(body).ok()?; + let uuid = parse_uuid(v.get("id")?.as_str()?)?; + let properties = v + .get("properties") + .and_then(|p| p.as_array()) + .into_iter() + .flatten() + .filter_map(|p| { + Some(horizon_protocol::packets::login::Property { + name: p.get("name")?.as_str()?.to_owned(), + value: p.get("value")?.as_str()?.to_owned(), + signature: p + .get("signature") + .and_then(|s| s.as_str()) + .map(str::to_owned), + }) + }) + .collect(); + Some(JoinedProfile { uuid, properties }) +} + #[cfg(test)] mod tests { use super::*; @@ -250,6 +331,20 @@ mod tests { path } + #[test] + fn verify_answers() { + assert_eq!(url_encode("Tester_1"), "Tester_1"); + assert_eq!(url_encode("-5a f"), "-5a+f"); + assert_eq!(url_encode("::1"), "%3A%3A1"); + let body = r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"e30=","signature":"c2ln"}]}"#; + let p = parse_joined(body).unwrap(); + assert_eq!(p.uuid, UUID); + assert_eq!(p.properties.len(), 1); + assert_eq!(p.properties[0].signature.as_deref(), Some("c2ln")); + assert_eq!(parse_joined(""), None); + assert_eq!(parse_joined(r#"{"name":"Notch"}"#), None); + } + #[test] fn session_files_are_read_once_and_must_be_private() { let dir = std::env::temp_dir().join(format!("horizon-auth-test-{}", std::process::id())); diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 79aa85204..6f1ba3fee 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -9,7 +9,7 @@ use super::{Game, Options, lan::LanSettings}; use horizon_client::{ Result, - lan::{LoginGate, NetConfig, hub::HubConfig}, + lan::{LoginGate, NetConfig, NetLog, OnlineMode, hub::HubConfig}, server::{ eula, java_properties::now_millis, @@ -60,6 +60,11 @@ static SETUP: OnceLock>> = OnceLock::new(); /// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`. pub(super) fn log(level: &str, message: &str) { + log_from("Server thread", level, message); +} + +/// A line from another of vanilla's threads (the login's User Authenticator). +fn log_from(thread: &str, level: &str, message: &str) { let file_level = match level { "WARN" => ::log::Level::Warn, "ERROR" => ::log::Level::Error, @@ -73,7 +78,7 @@ pub(super) fn log(level: &str, message: &str) { }); let secs = now_millis().div_euclid(1000).rem_euclid(86_400); println!( - "[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}", + "[{:02}:{:02}:{:02}] [{thread}/{level}]: {message}", secs / 3600, secs / 60 % 60, secs % 60 @@ -354,6 +359,19 @@ impl Game<'_> { ), ); let port = port.unwrap_or(props.server_port as u16); + // MinecraftServer.initializeKeyPair (only online mode uses it). + log("INFO", "Generating keypair"); + let online = if props.online_mode { + let key = horizon_protocol::rsa::RsaPrivateKey::generate(1024) + .map_err(|e| format!("Failed to generate key pair: {e}"))?; + Some(Arc::new(OnlineMode { + public_der: key.public_der(), + key, + prevent_proxy: props.prevent_proxy_connections, + })) + } else { + None + }; log( "INFO", &format!( @@ -365,27 +383,21 @@ impl Game<'_> { } ), ); - if props.online_mode { - // Authentication needs Mojang's session servers (an HTTPS client - // and RSA), which Horizon does not have yet: offline mode. + if online.is_none() { + log("WARN", "**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); log( "WARN", - "online-mode=true is not supported by Horizon yet: running in offline mode", + "The server will make no attempt to authenticate usernames. Beware.", + ); + log( + "WARN", + "While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.", + ); + log( + "WARN", + "To change this, set \"online-mode\" to \"true\" in the server.properties file.", ); } - log("WARN", "**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); - log( - "WARN", - "The server will make no attempt to authenticate usernames. Beware.", - ); - log( - "WARN", - "While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.", - ); - log( - "WARN", - "To change this, set \"online-mode\" to \"true\" in the server.properties file.", - ); let mut lists = Lists::load(); lists.use_whitelist = props.white_list; lists.enforce_whitelist = props.enforce_whitelist; @@ -451,6 +463,12 @@ impl Game<'_> { .any(|e| e.user.id == uuid && e.bypasses_player_limit) })), gate: Some(gate), + online, + log: Some(NetLog { + write: Arc::new(log_from), + lang: Arc::new(horizon_client::net::load_language(&self.options.resources)), + log_ips: props.log_ips, + }), }; let config = HubConfig { default_game_mode: game_mode, diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 16297e930..e5a5fe1e6 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -735,6 +735,7 @@ mod tab_list_tests { conn: uuid as u32, uuid, name: name.into(), + properties: Vec::new(), info: ClientInformation::new(8), brand: "test".into(), sender: PlayerSender { diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index 0688db0c6..d7c375dcd 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -1,4 +1,5 @@ -//! One accepted connection: handshake, status ping, offline-mode login and the +//! One accepted connection: handshake, status ping, login (offline, or online +//! with encryption and the session service's verdict) and the //! configuration phase (ServerStatusPacketListenerImpl, //! ServerLoginPacketListenerImpl, ServerConfigurationPacketListenerImpl). A //! player that completes configuration continues in the play state: the @@ -12,7 +13,7 @@ use super::{ use horizon_protocol::{ PROTOCOL_VERSION, connection::{ConnReader, ConnWriter, Connection}, - crypto::offline_uuid, + crypto::{offline_uuid, server_hash, uuid_string}, packets::{ Empty, configuration::{self as cfg, ClientInformation, KnownPack}, @@ -24,7 +25,7 @@ use std::{ net::TcpStream, sync::{ Arc, - atomic::{AtomicI32, AtomicI64, AtomicUsize, Ordering}, + atomic::{AtomicI32, AtomicI64, AtomicU32, AtomicUsize, Ordering}, mpsc::{Receiver, RecvTimeoutError, Sender, channel}, }, time::{Duration, Instant}, @@ -305,6 +306,145 @@ fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> { } } +/// ServerLoginPacketListenerImpl.getUserName: the name and the address +/// (Connection.getLoggableAddress, `/ip:port` as InetSocketAddress prints it). +fn user_name(name: &str, address: std::net::SocketAddr, log: &super::NetLog) -> String { + if log.log_ips { + format!("{name} (/{address})") + } else { + format!("{name} ()") + } +} + +/// ServerLoginPacketListenerImpl.disconnect: log the reason's text and send +/// it. Returns the text, for the "lost connection" line that follows. +fn refuse( + c: &mut Connection, + shared: &Shared, + thread: &str, + user: &str, + reason: &horizon_world::nbt::Tag, +) -> String { + let text = shared + .config + .log + .as_ref() + .map(|log| horizon_protocol::text::plain(reason, &log.lang)) + .unwrap_or_default(); + if let Some(log) = &shared.config.log { + (log.write)(thread, "INFO", &format!("Disconnecting {user}: {text}")); + } + login_disconnect(c, reason); + text +} + +/// ServerLoginPacketListenerImpl.onDisconnect, once the server thread sees +/// the connection closed: by a refusal, or by the client ("Disconnected"). +fn lost(shared: &Shared, user: &str, text: &str) { + if let Some(log) = &shared.config.log { + (log.write)( + "Server thread", + "INFO", + &format!("{user} lost connection: {text}"), + ); + } +} + +/// UNIQUE_THREAD_ID: the User Authenticator threads are numbered from 1. +static AUTHENTICATORS: AtomicU32 = AtomicU32::new(0); + +/// ServerLoginPacketListenerImpl.handleKey and the User Authenticator +/// thread: check the client's answer to the encryption request, encrypt the +/// connection, and ask the session service whether the player joined with +/// this server's hash. The profile, or the text of the refusal. +fn authenticate( + c: &mut Connection, + shared: &Shared, + online: &super::OnlineMode, + name: &str, + address: std::net::SocketAddr, + user: &str, +) -> Result), String>, String> { + let e = |e: horizon_protocol::Error| e.to_string(); + let mut challenge = [0u8; 4]; + horizon_protocol::crypto::random_bytes(&mut challenge).map_err(e)?; + c.send( + &login::Clientbound::Hello(login::Hello { + server_id: String::new(), + public_key: online.public_der.clone(), + challenge: challenge.to_vec(), + should_authenticate: true, + }) + .encode(), + ) + .map_err(e)?; + let (id, payload) = c.recv().map_err(e)?; + let key = match login::Serverbound::decode(id, &payload).map_err(e)? { + login::Serverbound::Key(k) => k, + _ => return Err("Unexpected packet during login".into()), + }; + // ServerboundKeyPacket.isChallengeValid and getSecretKey. + let protocol_error = || "Protocol error".to_owned(); + if online.key.decrypt(&key.challenge).ok().as_deref() != Some(&challenge[..]) { + return Err(protocol_error()); + } + let secret: [u8; 16] = online + .key + .decrypt(&key.key) + .ok() + .and_then(|s| s.try_into().ok()) + .ok_or_else(protocol_error)?; + let digest = server_hash("", &secret, &online.public_der); + c.enable_encryption(&secret); + let thread = format!( + "User Authenticator #{}", + AUTHENTICATORS.fetch_add(1, Ordering::Relaxed) + 1 + ); + let log = |level: &str, line: &str| { + if let Some(log) = &shared.config.log { + (log.write)(&thread, level, line); + } + }; + let ip = online.prevent_proxy.then(|| address.ip()); + match crate::auth::has_joined(name, &digest, ip) { + Ok(Some(profile)) => { + log( + "INFO", + &format!("UUID of player {name} is {}", uuid_string(profile.uuid)), + ); + Ok(Ok((profile.uuid, profile.properties))) + } + Ok(None) => { + let text = refuse( + c, + shared, + &thread, + user, + &translatable("multiplayer.disconnect.unverified_username", &[]), + ); + log( + "ERROR", + &format!("Username '{name}' tried to join with an invalid session"), + ); + Ok(Err(text)) + } + Err(_) => { + let text = refuse( + c, + shared, + &thread, + user, + &translatable("multiplayer.disconnect.authservers_down", &[]), + ); + log( + "ERROR", + "Couldn't verify username because servers are unavailable", + ); + Ok(Err(text)) + } + } +} + fn serve_login( mut c: Connection, address: std::net::SocketAddr, @@ -323,14 +463,36 @@ fn serve_login( ); return Ok(()); } - // Offline mode: the profile is derived from the name (PlayerList.canPlayerLogin - // then rejects duplicates and a full server). - let uuid = offline_uuid(&hello.name); + let user = shared + .config + .log + .as_ref() + .map(|log| user_name(&hello.name, address, log)) + .unwrap_or_default(); + // handleHello: online mode authenticates first; offline mode derives the + // profile from the name. + let (uuid, properties) = match &shared.config.online { + Some(online) => match authenticate(&mut c, shared, online, &hello.name, address, &user) { + Ok(Ok(profile)) => profile, + Ok(Err(refused)) => { + lost(shared, &user, &refused); + return Ok(()); + } + Err(err) => { + lost(shared, &user, "Disconnected"); + return Err(err); + } + }, + None => (offline_uuid(&hello.name), Vec::new()), + }; + // verifyLoginAndFinishConnectionSetup: PlayerList.canPlayerLogin, then + // duplicates and a full server. if let Some(reason) = shared.try_admit(address, uuid, &hello.name) { - login_disconnect(&mut c, &reason); + let text = refuse(&mut c, shared, "Server thread", &user, &reason); + lost(shared, &user, &text); return Ok(()); } - let result = login_and_configure(&mut c, shared, uuid, &hello.name); + let result = login_and_configure(&mut c, shared, uuid, &hello.name, properties); match result { Ok(Some(parts)) => { play(c, shared, parts, address); @@ -342,6 +504,9 @@ fn serve_login( } Err(err) => { shared.release(uuid); + // ServerConfigurationPacketListenerImpl.onDisconnect. + let profile = format!("{} ({})", hello.name, uuid_string(uuid)); + lost(shared, &profile, "Disconnected"); Err(err) } } @@ -350,6 +515,7 @@ fn serve_login( struct Parts { uuid: u128, name: String, + properties: Vec, info: ClientInformation, brand: String, } @@ -359,6 +525,7 @@ fn login_and_configure( shared: &Arc, uuid: u128, name: &str, + properties: Vec, ) -> Result, String> { let e = |e: horizon_protocol::Error| e.to_string(); let threshold = shared.config.compression_threshold; @@ -372,7 +539,7 @@ fn login_and_configure( profile: login::GameProfile { uuid, name: name.to_owned(), - properties: Vec::new(), + properties: properties.clone(), }, session: uuid, }) @@ -451,6 +618,7 @@ fn login_and_configure( Ok(Some(Parts { uuid, name: name.to_owned(), + properties, info, brand, })) @@ -480,6 +648,7 @@ fn play(c: Connection, shared: &Arc, parts: Parts, address: std::net::So conn: conn_id, uuid: parts.uuid, name: parts.name, + properties: parts.properties, info: parts.info, brand: parts.brand, sender, diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 954ffc714..c6215df70 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -36,6 +36,8 @@ pub struct Guest { pub left_reason: String, pub uuid: u128, pub name: String, + /// The profile's properties, for the player list (skins). + pub properties: Vec, pub entity_id: i32, pub sender: PlayerSender, pub latency: Arc, @@ -130,6 +132,7 @@ impl Guest { left_reason: String::new(), uuid: j.uuid, name: j.name, + properties: j.properties, entity_id, sender: j.sender, latency: j.latency, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index fcae7c097..e43d47541 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -389,7 +389,12 @@ impl Hub { play::PlayerInfo { uuid, name: Some(name.to_owned()), - properties: Vec::new(), + properties: self + .guests + .iter() + .find(|g| g.uuid == uuid) + .map(|g| g.properties.clone()) + .unwrap_or_default(), chat_session: None, game_mode: Some(mode), listed: Some(true), diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index f4211c6ea..fb9bd5f4c 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -58,6 +58,8 @@ pub struct Joined { pub conn: u32, pub uuid: u128, pub name: String, + /// The profile's properties (skin textures, in online mode). + pub properties: Vec, pub info: ClientInformation, pub brand: String, pub sender: PlayerSender, @@ -79,6 +81,27 @@ pub enum Out { pub type LoginGate = Arc Option + Send + Sync>; +/// online-mode=true: the key pair the server made at startup +/// (MinecraftServer.initializeKeyPair) and how players are verified. +pub struct OnlineMode { + pub key: horizon_protocol::rsa::RsaPrivateKey, + /// The public key as X.509 (PublicKey.getEncoded), sent in the hello. + pub public_der: Vec, + /// prevent-proxy-connections: the session service also checks the address. + pub prevent_proxy: bool, +} + +/// The dedicated server's log for the login phase: (thread, level, line) +/// written as vanilla's Log4j would, and the language that turns a +/// disconnect reason into its text (Component.getString). +#[derive(Clone)] +pub struct NetLog { + pub write: Arc, + pub lang: Arc, + /// log-ips: addresses in the log, or "". + pub log_ips: bool, +} + /// How the server side of the network behaves: an integrated server's LAN /// uses the defaults, a dedicated server takes them from server.properties. #[derive(Clone)] @@ -107,6 +130,9 @@ pub struct NetConfig { /// Ops bypass a full server (ServerOpList.canBypassPlayerLimit). pub bypasses_limit: Option bool + Send + Sync>>, pub gate: Option, + /// Online mode: players are authenticated (none on a LAN world). + pub online: Option>, + pub log: Option, } impl NetConfig { /// IntegratedServer.publishServer. @@ -126,6 +152,8 @@ impl NetConfig { listen: true, bypasses_limit: None, gate: None, + online: None, + log: None, } } } diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index 57443e4fd..fe31e425e 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -1,7 +1,9 @@ //! RSA for the online-mode login: the server's X.509 public key //! (Crypt.byteToPublicKey) and PKCS#1 v1.5 encryption of the shared secret //! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher = -//! RSA/ECB/PKCS1Padding). Modular exponentiation uses Montgomery +//! RSA/ECB/PKCS1Padding), and on the server's side the key pair it makes at +//! startup (Crypt.generateKeyPair: 1024 bits) and the decryption +//! (Crypt.decryptUsingKey). Modular exponentiation uses Montgomery //! multiplication on 32-bit limbs; RSA moduli are always odd. use crate::{Error, Result}; @@ -43,6 +45,46 @@ impl Big { } true } + /// self · other, as many limbs as both together. + fn mul(&self, other: &Self) -> Self { + let mut out = vec![0u32; self.0.len() + other.0.len()]; + for (i, &a) in self.0.iter().enumerate() { + let mut carry = 0u64; + for (j, &b) in other.0.iter().enumerate() { + let t = u64::from(out[i + j]) + u64::from(a) * u64::from(b) + carry; + out[i + j] = t as u32; + carry = t >> 32; + } + out[i + other.0.len()] = carry as u32; + } + Self(out) + } + /// self · m + a, one limb longer. + fn mul_small_add(&self, m: u32, a: u32) -> Self { + let mut out = Vec::with_capacity(self.0.len() + 1); + let mut carry = u64::from(a); + for &l in &self.0 { + let t = u64::from(l) * u64::from(m) + carry; + out.push(t as u32); + carry = t >> 32; + } + out.push(carry as u32); + Self(out) + } + /// (self / d, self mod d). + fn div_small(&self, d: u32) -> (Self, u32) { + let mut out = vec![0u32; self.0.len()]; + let mut rem = 0u64; + for i in (0..self.0.len()).rev() { + let t = rem << 32 | u64::from(self.0[i]); + out[i] = (t / u64::from(d)) as u32; + rem = t % u64::from(d); + } + (Self(out), rem as u32) + } + fn is_one(&self) -> bool { + self.0.first() == Some(&1) && self.0[1..].iter().all(|&l| l == 0) + } fn sub_assign(&mut self, other: &Self) { let mut borrow = 0i64; for (a, b) in self.0.iter_mut().zip(&other.0) { @@ -249,6 +291,198 @@ impl RsaPublicKey { } } +/// Small odd primes for sieving prime candidates. +const SMALL_PRIMES: [u32; 53] = [ + 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, + 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, + 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, +]; +/// Miller-Rabin rounds: a composite passes all of them with odds below 2⁻⁸⁰. +const ROUNDS: usize = 40; +const E: u32 = 65537; + +/// A random odd number of `limbs` limbs with its two top bits set, so two of +/// them multiply to exactly twice the bits. +fn candidate(limbs: usize) -> Result { + let mut bytes = vec![0u8; limbs * 4]; + crate::crypto::random_bytes(&mut bytes)?; + bytes[0] |= 0xC0; + bytes[limbs * 4 - 1] |= 1; + Ok(Big::from_be_bytes(&bytes, limbs)) +} + +/// Miller-Rabin with random bases. +fn probably_prime(p: &Big) -> Result { + if SMALL_PRIMES.iter().any(|&q| p.div_small(q).1 == 0) { + return Ok(false); + } + let k = p.0.len(); + let mont = Mont::new(p.clone()); + let mut p_minus_one = p.clone(); + p_minus_one.0[0] -= 1; // p is odd + let s = (0..k * 32).find(|&i| p_minus_one.bit(i)).unwrap_or(0); + // d = (p - 1) >> s + let mut d = Big(vec![0; k]); + for i in 0..k * 32 - s { + if p_minus_one.bit(i + s) { + d.0[i / 32] |= 1 << (i % 32); + } + } + let mut two = Big(vec![0; k]); + two.0[0] = 2; + 'rounds: for _ in 0..ROUNDS { + // A random base in [2, p - 2]. + let mut a = candidate(k)?; + a.0[k - 1] %= p.0[k - 1]; + if !a.ge(&two) || a.ge(&p_minus_one) { + continue; + } + let mut x = mont.pow(&a, &d); + if x.is_one() || x == p_minus_one { + continue; + } + for _ in 1..s { + x = mont.pow(&x, &two); + if x == p_minus_one { + continue 'rounds; + } + if x.is_one() { + return Ok(false); + } + } + return Ok(false); + } + Ok(true) +} + +/// A prime of `limbs` limbs whose p - 1 is prime to E. +fn prime(limbs: usize) -> Result { + loop { + let p = candidate(limbs)?; + if p.div_small(E).1 != 1 && probably_prime(&p)? { + return Ok(p); + } + } +} + +/// DER: a tag and its length, then the contents. +fn der_element(tag: u8, contents: &[u8]) -> Vec { + let mut out = vec![tag]; + let len = contents.len(); + if len < 0x80 { + out.push(len as u8); + } else { + let bytes: Vec = len + .to_be_bytes() + .into_iter() + .skip_while(|&b| b == 0) + .collect(); + out.push(0x80 | bytes.len() as u8); + out.extend(bytes); + } + out.extend_from_slice(contents); + out +} + +/// A DER INTEGER from big-endian magnitude bytes (a leading zero keeps it positive). +fn der_integer(magnitude: &[u8]) -> Vec { + let mut v = strip(magnitude); + if v.first().is_none_or(|b| b & 0x80 != 0) { + v.insert(0, 0); + } + der_element(0x02, &v) +} + +/// The server's key pair (Crypt.generateKeyPair). +pub struct RsaPrivateKey { + pub public: RsaPublicKey, + /// The private exponent, big-endian. + exponent: Vec, +} + +impl std::fmt::Debug for RsaPrivateKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RsaPrivateKey") + .field("public", &self.public) + .finish_non_exhaustive() + } +} + +impl RsaPrivateKey { + /// A new key pair with a `bits`-bit modulus (a multiple of 64) and + /// public exponent 65537, as Java's RSA KeyPairGenerator makes. + pub fn generate(bits: usize) -> Result { + let limbs = bits / 64; + let p = prime(limbs)?; + let q = loop { + let q = prime(limbs)?; + if q != p { + break q; + } + }; + let n = p.mul(&q); + // d = (1 + k·φ) / E with k making it whole: k ≡ -φ⁻¹ (mod E). + let (mut p1, mut q1) = (p, q); + p1.0[0] -= 1; + q1.0[0] -= 1; + let phi = p1.mul(&q1); + let r = u64::from(phi.div_small(E).1); + let inverse = (1..u64::from(E)) + .find(|k| k * r % u64::from(E) == 1) + .ok_or_else(|| Error::new("RSA key generation failed"))?; + let k = (u64::from(E) - inverse) as u32; + let (d, rem) = phi.mul_small_add(k, 1).div_small(E); + if rem != 0 { + return Err(Error::new("RSA key generation failed")); + } + let size = bits / 8; + Ok(Self { + public: RsaPublicKey { + modulus: strip(&n.to_be_bytes(size)), + exponent: strip(&E.to_be_bytes()), + }, + exponent: d.to_be_bytes(size), + }) + } + + /// PublicKey.getEncoded: X.509 SubjectPublicKeyInfo. + pub fn public_der(&self) -> Vec { + let key = der_element( + 0x30, + &[ + der_integer(&self.public.modulus), + der_integer(&self.public.exponent), + ] + .concat(), + ); + let algorithm = der_element( + 0x30, + &[der_element(0x06, RSA_ENCRYPTION), vec![0x05, 0x00]].concat(), + ); + let bits = der_element(0x03, &[&[0u8][..], &key].concat()); + der_element(0x30, &[algorithm, bits].concat()) + } + + /// Crypt.decryptUsingKey: RSAES-PKCS1-v1_5 decryption (RFC 8017 7.2.2). + pub fn decrypt(&self, ciphertext: &[u8]) -> Result> { + let bad = || Error::new("Decryption error"); + let k = self.public.size(); + // The modulus has no leading zero, so equal lengths compare as numbers. + if ciphertext.len() != k || ciphertext >= self.public.modulus.as_slice() { + return Err(bad()); + } + let block = self.public.apply(ciphertext, &self.exponent); + if block[0] != 0 || block[1] != 2 { + return Err(bad()); + } + let zero = block[2..].iter().position(|&b| b == 0).ok_or_else(bad)? + 2; + if zero < 10 { + return Err(bad()); + } + Ok(block[zero + 1..].to_vec()) + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -316,6 +550,50 @@ pub(crate) mod tests { assert!(key.encrypt(&[0; 118]).is_err()); } + /// A key made here: Java-style DER that parses back, and what its public + /// half encrypts its private half decrypts. + #[test] + fn generated_keys_round_trip() { + let key = RsaPrivateKey::generate(1024).unwrap(); + assert_eq!(key.public.size(), 128); + assert_eq!(key.public.exponent, vec![1, 0, 1]); + let der = key.public_der(); + assert_eq!( + &der[..3], + &[0x30, 0x81, 0x9f], + "a 1024-bit SubjectPublicKeyInfo" + ); + assert_eq!(RsaPublicKey::from_der(&der).unwrap(), key.public); + for message in [&[0x5au8; 16][..], &[1, 2, 3, 4], &[]] { + let c = key.public.encrypt(message).unwrap(); + assert_eq!(key.decrypt(&c).unwrap(), message); + } + assert!(key.decrypt(&[0u8; 128]).is_err()); + assert!(key.decrypt(&[1u8; 64]).is_err()); + } + + #[test] + fn decrypts_with_a_known_key() { + let key = RsaPrivateKey { + public: RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(), + exponent: hex(TEST_D), + }; + let c = key.public.encrypt(b"secret").unwrap(); + assert_eq!(key.decrypt(&c).unwrap(), b"secret"); + } + + #[test] + fn finds_primes() { + let p = Big(vec![0xFFFF_FFFB]); // 2^32 - 5 is prime + assert!(probably_prime(&p).unwrap()); + assert!(!probably_prime(&Big(vec![0xFFFF_FFFD])).unwrap()); // 3 · 1431655765 + // 2^61 - 1 (prime) and a Carmichael-free composite 2^61 + 1. + let m61 = (1u64 << 61) - 1; + assert!(probably_prime(&Big(vec![m61 as u32, (m61 >> 32) as u32])).unwrap()); + let c = (1u64 << 61) + 1; + assert!(!probably_prime(&Big(vec![c as u32, (c >> 32) as u32])).unwrap()); + } + /// An OpenSSL signature checked with the public exponent: the block ends /// with SHA-256("hello"), so the modular arithmetic agrees with OpenSSL's. #[test] diff --git a/docs/server.md b/docs/server.md index 6e165f534..0eb0aaf35 100644 --- a/docs/server.md +++ b/docs/server.md @@ -76,9 +76,9 @@ not tick cost, so it is in scope here (see section 9). | Area | Status | |---|---| -| `online-mode=true` | **Not supported.** The server logs a warning and runs offline: no session `hasJoined` check, no encryption, no secure chat. (The client side of online mode works and is tested by `test_online_mode_parity.py` against vanilla's server.) A public server must not run like this. This is the top engine item. | +| `online-mode=true` | **Works** (ServerLoginPacketListenerImpl): a 1024-bit RSA key pair at start ("Generating keypair"), the encryption request, the shared secret and challenge, AES/CFB8, and the session service's `hasJoined` check (with the address when `prevent-proxy-connections` is on), with vanilla's log lines and messages. `test_online_mode_parity.py` runs the same logins against vanilla's server and Horizon's with a mock session service. Not yet: secure chat (chat is unsigned, as on a server that doesn't enforce it). | | Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. | -| Refused logins | Nothing is logged. Vanilla logs `Disconnecting : ` (`ServerLoginPacketListenerImpl.disconnect`) and ` lost connection: …`. | +| Refused logins | Logged as vanilla does: `Disconnecting (/address): `, then ` (/address) lost connection: `, and the session errors (`Username '' tried to join with an invalid session`, `Couldn't verify username because servers are unavailable`). | | Gameplay for remote players | The LAN guest leftovers apply: an item used on a block is used twice, the recipe book doesn't work, status effects don't apply to guests, arrows don't record their owner, team friendly fire is ignored (#484). Block desync and short freezes are reported on a same-machine server (#500). | | Defaults that surprise owners | `white-list=true` is vanilla 26.3's default, so a fresh server refuses everyone until they are added. That matches vanilla, so the first-run flow (section 3) asks about the whitelist up front. | | Management | Only stdin. There is no service, no backups, no status beyond `list`, no restart after a crash, and a server can't be managed while it runs in the background. | @@ -239,7 +239,7 @@ motd = "A Minecraft Server" port = 25565 bind = "" # listen on every address, or only on this one (server-ip) max_players = 20 -online_mode = true # not supported by Horizon yet: the server runs offline and says so +online_mode = true # check players' Minecraft accounts (false: anyone joins under any name) whitelist = true # only whitelisted players and operators can join enforce_whitelist = false # kick online players taken off the whitelist view_distance = 10 @@ -487,7 +487,7 @@ machine, then published in `benchmarks/`; and item 5. **Out (next):** -- online mode on the server side (session `hasJoined`, encryption, secure chat); +- secure chat on the server (online mode itself works); - the Nether and End for remote players; - the headless engine and its RAM win; - a server-only prepare without a JDK; @@ -497,8 +497,8 @@ machine, then published in `benchmarks/`; and item 5. - the website's "host a server" page; - retiring `tools/server.py` and `docs/server-quickstart.txt` (once the benchmark replaces them). -Until online mode works, the docs say to run Horizon's server only on a LAN, a tailnet, or behind a -whitelist. +Online mode works, so a public server can check accounts. An offline server should still run only on a +LAN, a tailnet, or behind a whitelist. ## 11. Pull requests diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py index 45b4b3ac6..8e349bf0d 100644 --- a/tools/test_online_mode_parity.py +++ b/tools/test_online_mode_parity.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Horizon's client joins vanilla's online-mode server, with no real account. +"""Horizon's client joins vanilla's online-mode server and Horizon's, with no real account. A small mock of the Minecraft services (dev only: the discovery document and the session service's join and hasJoined endpoints) stands in for Mojang's. @@ -20,7 +20,13 @@ in the world with its chunks, chats, runs /list, leaves). Also checked, with vanilla's messages: - a token the session service rejects ("Failed to log in: Invalid session"); - a join the session service forgets (the server: "Failed to verify username!"); -- no account at all (the client refuses before joining). +- no account at all (the client refuses before joining); +- a verified player the whitelist refuses. + +Horizon's dedicated server then runs the same steps in online mode +(`HORIZON_API_DISCOVERY` points it at the mock too): it must give the client +the same answers and log the same lines about the player as vanilla's +("UUID of player ...", "Disconnecting ...", "... lost connection: ..."). Chat is unsigned here: the mock serves no Mojang public keys, so the server can't validate profile keys and doesn't enforce secure chat. @@ -31,9 +37,11 @@ import os from pathlib import Path import platform import shutil +import re import subprocess import sys import threading +import time import urllib.parse try: @@ -167,43 +175,42 @@ def run_client(binary, build, port, label, token, discovery): got['session file left'] = (directory / 'session.json').exists() return got +# The server's lines about the player, as both servers print them. +PLAYER_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*(?:Tester|Username|Disconnecting|verify username).*)$') -def main(): - lock, jars, libraries = base.verify_artifacts() - build = lab.LOCAL / NAME - build.mkdir(parents=True, exist_ok=True) - report = build / 'report.json' - report.unlink(missing_ok=True) - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, - 'compile-rust') - metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], - cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - services = Services() - discovery = services.url + '/minecraft/client' +def player_lines(lines): + out = [] + for line in lines: + if m := PLAYER_LINE.match(line): + text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2)) + text = re.sub(r'entity id \d+ at \(.*\)', 'entity id _ at _', text) + out.append(f'[{m.group(1)}] {text}') + return out + + +def run_side(label, command, binary, build, services, discovery): + """The five logins against one server; its checks and its log about the player.""" port = free_port() - directory = build / 'server' + directory = build / label shutil.rmtree(directory, ignore_errors=True) directory.mkdir() props = dict(PROPERTIES, **{'server-port': str(port)}) (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) (directory / 'eula.txt').write_text('eula=true\n') - command = ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}', - '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] - server = Server(command, directory, 'vanilla-online') + os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery) + server = Server(command, directory, f'{label}-online') checks = [] - def check(label, actual, expected): - checks.append(f'{label}: ' + ('ok' if actual == expected else f'expected {expected!r}, got {actual!r}')) + def check(name, actual, expected): + checks.append(f'{name}: ' + ('ok' if actual == expected else f'expected {expected!r}, got {actual!r}')) try: server.wait_for(r'Done \(', timeout=600) services.take_log() # 1. Signed in: the full encrypted handshake, then play. - got = run_client(binary, build, port, 'signed-in', GOOD, discovery) + got = run_client(binary, build, port, f'{label}-signed-in', GOOD, discovery) server.wait_for(r'Tester left the game', timeout=30) log = services.take_log() joins = [e for e in log if e[0] == 'join'] @@ -227,27 +234,71 @@ def main(): # 2. A token the session service rejects: vanilla's message, no key sent. mark = len(server.lines) - got = run_client(binary, build, port, 'rejected', BAD, discovery) + got = run_client(binary, build, port, f'{label}-rejected', BAD, discovery) check('rejected token: client message', got['error'], 'disconnected: Failed to log in: Invalid session (Try restarting your game and the launcher)') check('rejected token: no verification', [e[0] for e in services.take_log()], ['join']) # 3. The session service forgets the join: the server refuses the player. - got = run_client(binary, build, port, 'forgotten', FORGET, discovery) + got = run_client(binary, build, port, f'{label}-forgotten', FORGET, discovery) server.wait_for(r'Failed to verify username', timeout=30) check('forgotten join: client message', got['error'], 'disconnected: Failed to verify username!') check('forgotten join: server verified and refused', [(e[0], e[3]) for e in services.take_log()], [('join', True), ('verify', False)]) # 4. No account: refused by the client before anything is sent to the services. - got = run_client(binary, build, port, 'no-account', None, discovery) + got = run_client(binary, build, port, f'{label}-no-account', None, discovery) check('no account: client message', got['error'] or '', 'disconnected: This server is in online mode. ' 'Sign in with your Microsoft account in the Horizon launcher to join it.') check('no account: no service calls', services.take_log(), []) check('no player joined after the first', 'joined the game' in '\n'.join(server.lines[mark:]), False) + + # 5. Verified, but not on the whitelist. + server.console('whitelist on') + server.wait_for(r'Whitelist is now turned on', timeout=30) + got = run_client(binary, build, port, f'{label}-not-whitelisted', GOOD, discovery) + server.wait_for(r'Disconnecting Tester', timeout=30) + check('not whitelisted: client message', got['error'], 'disconnected: You are not white-listed on this server!') + check('not whitelisted: verified first', [(e[0], e[3]) for e in services.take_log()], + [('join', True), ('verify', True)]) + time.sleep(1) finally: server.stop() + return checks, player_lines(server.lines) + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + + services = Services() + discovery = services.url + '/minecraft/client' + vanilla = ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}', + '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + checks, transcripts = [], {} + try: + for label, command in [('vanilla', vanilla), ('horizon', horizon)]: + side_checks, transcripts[label] = run_side(label, command, binary, build, services, discovery) + checks += [f'{label}: {c}' for c in side_checks] + finally: services.stop() + for label in transcripts: + (build / f'{label}.txt').write_text('\n'.join(transcripts[label]) + '\n', encoding='utf-8') + if 'horizon' in transcripts: + import difflib + diff = [l for l in difflib.unified_diff(transcripts['vanilla'], transcripts['horizon'], 'vanilla', 'horizon', + n=0, lineterm='') if l[:1] in '+-' and l[:3] not in ('+++', '---')] + checks.append('server log about the player: ' + ('ok' if not diff else 'differs:\n ' + '\n '.join(diff))) for line in checks: print(line) @@ -257,8 +308,9 @@ def main(): lab.write_json(report, dict( schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], checks=len(checks), - scope='Online-mode login against vanilla\'s dedicated server and a mock session service: server hash, ' - 'RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten join, no account.')) + scope='Online-mode login against vanilla\'s dedicated server and Horizon\'s, with a mock session service: ' + 'server hash, RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten ' + 'join, no account, whitelist; the servers\' log lines about the player.')) print(f'online mode: {len(checks)} checks ok') From ae22d5dd960c930f0fefc42b337d9c066e4af1be Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:33:21 +0200 Subject: [PATCH 006/327] Online mode: players named in commands are their accounts An online-mode server checks players by their account's UUID, so op, whitelist, ban and pardon now resolve a name as vanilla's CachedUserNameToIdResolver does: a player on the server, then one seen since the start (in memory; vanilla also keeps usercache.json), then the services' profiles/getByName endpoint through the discovery document. A name with no account is "That player does not exist", with vanilla's "Couldn't find profile with name" warning. Offline servers keep the offline profiles. horizon-server does the same while the server is stopped (op, whitelist add, and the players init writes), and removes entries by the name already on the list. `init --offline` (or HORIZON_ONLINE=false) sets online-mode off; init's note now warns about offline servers only. The online-mode harness adds a sixth login: `whitelist add` for the player who joined earlier needs no lookup and lets them in, and an unknown name is looked up and refused, on vanilla's server and on Horizon's (43 checks). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-client/src/game/dedicated.rs | 100 ++++++++++++++------ crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-server-files/Cargo.toml | 4 +- crates/horizon-server-files/src/lib.rs | 8 +- crates/horizon-server-files/src/profiles.rs | 100 ++++++++++++++++++++ crates/horizon-server/src/config.rs | 2 +- crates/horizon-server/src/init.rs | 36 ++++--- crates/horizon-server/src/lists.rs | 27 +++++- crates/horizon-server/src/main.rs | 3 +- tools/test_online_mode_parity.py | 53 ++++++++++- 11 files changed, 282 insertions(+), 53 deletions(-) create mode 100644 crates/horizon-server-files/src/profiles.rs diff --git a/Cargo.lock b/Cargo.lock index 1d5897d11..aadf1e1c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1573,6 +1573,7 @@ dependencies = [ "horizon-protocol", "horizon-world", "log", + "ureq", ] [[package]] diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 6f1ba3fee..9bc1e1fce 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -58,6 +58,21 @@ struct Setup { } static SETUP: OnceLock>> = OnceLock::new(); +/// CachedUserNameToIdResolver, kept in memory only (vanilla also saves it to +/// usercache.json): players who joined, and accounts found by name, by name +/// in lower case. +static USER_CACHE: OnceLock>> = OnceLock::new(); + +/// PlayerList.placeNewPlayer adds the player to the name cache. +pub(super) fn remember(name: &str, uuid: u128) { + let user = NameAndId { + id: uuid, + name: name.to_owned(), + }; + let cache = USER_CACHE.get_or_init(Default::default); + cache.lock().unwrap().insert(name.to_lowercase(), user); +} + /// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`. pub(super) fn log(level: &str, message: &str) { log_from("Server thread", level, message); @@ -316,6 +331,8 @@ struct ServerState { /// When the last passes of the loop ended, for the tick rate horizon-server shows. ticks: std::collections::VecDeque, paused: bool, + /// online-mode: names given to commands are looked up as accounts. + online: bool, } impl Game<'_> { @@ -512,6 +529,7 @@ impl Game<'_> { empty_ticks: 0, ticks: Default::default(), paused: false, + online: props.online_mode, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -640,23 +658,46 @@ impl Game<'_> { host.hub.resend_commands(); } - /// A known player by name: online first, else the offline profile. - fn resolve(&self, name: &str) -> NameAndId { - self.lan - .as_ref() - .and_then(|h| { - h.hub - .guests - .iter() - .find(|g| g.name.eq_ignore_ascii_case(name)) - }) - .map_or_else( - || NameAndId::offline(name), - |g| NameAndId { - id: g.uuid, - name: g.name.clone(), - }, - ) + /// A player on the server, by name. + fn online_player(&self, name: &str) -> Option { + let hub = &self.lan.as_ref()?.hub; + let g = hub + .guests + .iter() + .find(|g| g.name.eq_ignore_ascii_case(name))?; + Some(NameAndId { + id: g.uuid, + name: g.name.clone(), + }) + } + + /// GameProfileArgument: a player on the server, else one seen since the + /// start, else the name resolved as the server's mode says (an online + /// server asks the services, an offline one makes the offline profile). + /// None, told to the console: no such account. + fn resolve(&self, name: &str, online: bool) -> Option { + let user = self.online_player(name).or_else(|| { + let key = name.to_lowercase(); + let cache = USER_CACHE.get_or_init(Default::default); + if let Some(user) = cache.lock().unwrap().get(&key) { + return Some(user.clone()); + } + let user = horizon_server_files::profiles::resolve(name, online); + let Some(user) = user else { + if online { + log("WARN", &format!("Couldn't find profile with name: {key}")); + } + return None; + }; + if online { + cache.lock().unwrap().insert(key, user.clone()); + } + Some(user) + }); + if user.is_none() { + self.console_reply(Text::translate("argument.player.unknown", &[])); + } + user } /// MinecraftServer.sendSystemMessage: what the console is told. @@ -739,7 +780,9 @@ impl Game<'_> { )); } "op" | "deop" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0], state.online) else { + return; + }; let level = 4; let changed = { let mut l = state.lists.lock().unwrap(); @@ -769,7 +812,9 @@ impl Game<'_> { } "whitelist" => self.console_whitelist(state, &rest), "ban" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0], state.online) else { + return; + }; let reason = (rest.len() > 1).then(|| rest[1..].join(" ")); let added = state.lists.lock().unwrap().bans.add(BanEntry::new( user.clone(), @@ -859,7 +904,9 @@ impl Game<'_> { } } "pardon" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0], state.online) else { + return; + }; let removed = state.lists.lock().unwrap().bans.remove(&user); let key = if removed { "commands.pardon.success" @@ -925,15 +972,10 @@ impl Game<'_> { } } "kick" if !rest.is_empty() => { - let user = self.resolve(rest[0]); - let online = self - .lan - .as_ref() - .is_some_and(|h| h.hub.guests.iter().any(|g| g.uuid == user.id)); - if !online { + let Some(user) = self.online_player(rest[0]) else { self.console_reply(Text::translate("argument.entity.notfound.player", &[])); return; - } + }; let reason = if rest.len() > 1 { Tag::String(JavaString::from(rest[1..].join(" ").as_str())) } else { @@ -1013,7 +1055,9 @@ impl Game<'_> { self.console_reply(Text::translate("commands.whitelist.reloaded", &[])); } ["add", name] | ["remove", name] => { - let user = self.resolve(name); + let Some(user) = self.resolve(name, state.online) else { + return; + }; let mut l = state.lists.lock().unwrap(); let (ok, key) = if rest[0] == "add" { if l.white.contains(&user) { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index c416c202f..3e570f5ef 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -673,6 +673,7 @@ impl Game<'_> { && let Some(g) = host.hub.guest(conn) { // PlayerList.placeNewPlayer, then the broadcast join message. + super::dedicated::remember(&g.name, g.uuid); let [x, y, z] = g.position; super::dedicated::log( "INFO", diff --git a/crates/horizon-server-files/Cargo.toml b/crates/horizon-server-files/Cargo.toml index 52114718d..184dadc90 100644 --- a/crates/horizon-server-files/Cargo.toml +++ b/crates/horizon-server-files/Cargo.toml @@ -4,13 +4,15 @@ version = "0.1.0" edition.workspace = true license.workspace = true rust-version = "1.90" -description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans" +description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans, and account lookups" [dependencies] horizon-core = { path = "../horizon-core" } horizon-protocol = { path = "../horizon-protocol" } horizon-world = { path = "../horizon-world" } log = "0.4" +# Online mode: finding accounts by name (the services' profiles endpoint). +ureq = { version = "2", default-features = false, features = ["tls"] } [lints] workspace = true diff --git a/crates/horizon-server-files/src/lib.rs b/crates/horizon-server-files/src/lib.rs index 30c75c869..babb02771 100644 --- a/crates/horizon-server-files/src/lib.rs +++ b/crates/horizon-server-files/src/lib.rs @@ -1,10 +1,12 @@ //! The dedicated server's files and settings, ported from //! net.minecraft.server.dedicated and net.minecraft.server.players: -//! server.properties, eula.txt and the four user lists. The game's dedicated -//! server (`horizon-client --dedicated`) reads them, and `horizon-server` -//! manages them; this crate needs neither a window nor the game. +//! server.properties, eula.txt, the four user lists and looking players up +//! by name in online mode. The game's dedicated server +//! (`horizon-client --dedicated`) reads them, and `horizon-server` manages +//! them; this crate needs neither a window nor the game. pub mod eula; pub mod java_properties; pub mod json; +pub mod profiles; pub mod properties; pub mod user_lists; diff --git a/crates/horizon-server-files/src/profiles.rs b/crates/horizon-server-files/src/profiles.rs new file mode 100644 index 000000000..a093fbfb1 --- /dev/null +++ b/crates/horizon-server-files/src/profiles.rs @@ -0,0 +1,100 @@ +//! Finding a player's account by name, as an online-mode server does for the +//! names given to `op`, `whitelist` and `ban` (CachedUserNameToIdResolver, +//! MinecraftServicesProfileRepository.findProfileByName): the services' +//! `profiles` / `getByName` endpoint, found through the discovery document. +use crate::{ + json::{self, Json}, + user_lists::NameAndId, +}; +use std::time::Duration; + +/// Mojang's services discovery document. +pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client"; + +/// The discovery document's URL: `HORIZON_API_DISCOVERY` overrides it like +/// authlib's `-Dminecraft.api.discovery.host`. +pub fn discovery_url() -> String { + std::env::var("HORIZON_API_DISCOVERY") + .ok() + .filter(|u| !u.is_empty()) + .unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned()) +} + +/// StringUtil.isValidPlayerName: at most 16 UTF-16 units, none a control +/// character, a space or above ASCII. +pub fn valid_player_name(name: &str) -> bool { + name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127) +} + +/// How a server resolves a name it was given (CachedUserNameToIdResolver.get, +/// without the usercache.json cache): an offline server makes the offline +/// profile; an online one asks the services (for the name in lower case) and +/// knows nobody they don't. +pub fn resolve(name: &str, online: bool) -> Option { + if online && valid_player_name(name) { + find_by_name(&discovery_url(), &name.to_ascii_lowercase()) + } else { + (!online).then(|| NameAndId::offline(name)) + } +} + +/// MinecraftServicesProfileRepository.findProfileByName: the account named +/// `name` (any case), or None when there is none or the services don't +/// answer (vanilla logs both as "Couldn't find profile with name"). +pub fn find_by_name(discovery: &str, name: &str) -> Option { + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(15)) + .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .build(); + let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?; + let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase()); + found(&agent.get(&url).call().ok()?.into_string().ok()?, name) +} + +/// MinecraftServicesDiscoveryService.getUrl(service, endpoint). +fn endpoint(doc: &Json, service: &str, name: &str) -> Option { + doc.get("discovery")? + .get(service)? + .get("endpoints")? + .get(name)? + .get("uri")? + .as_string() +} + +/// The answer, authlib's NameAndId: `{"id", "name"}`, the id undashed. +pub fn found(answer: &str, name: &str) -> Option { + let profile = json::parse(answer, true).ok()?; + let found = profile.get("name")?.as_string()?; + let id = profile.get("id")?.as_string()?.replace('-', ""); + (found.eq_ignore_ascii_case(name) && id.len() == 32).then_some(())?; + Some(NameAndId { + id: u128::from_str_radix(&id, 16).ok()?, + name: found, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_answers() { + assert!(valid_player_name("Alex_123")); + assert!(!valid_player_name("two words")); + assert!(!valid_player_name("ThisNameIsTooLong")); + assert!(!valid_player_name("caf\u{e9}")); + assert_eq!(resolve("Alex", false), Some(NameAndId::offline("Alex"))); + assert_eq!(resolve("not valid", true), None); + let answer = r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"#; + assert_eq!( + found(answer, "notch"), + Some(NameAndId { + id: 0x069a79f444e94726a5befca90e38aaf5, + name: "Notch".into() + }) + ); + assert_eq!(found(answer, "Steve"), None); + assert_eq!(found("{}", "Notch"), None); + assert_eq!(found("", "Notch"), None); + } +} diff --git a/crates/horizon-server/src/config.rs b/crates/horizon-server/src/config.rs index c62869e27..3c389f858 100644 --- a/crates/horizon-server/src/config.rs +++ b/crates/horizon-server/src/config.rs @@ -23,7 +23,7 @@ motd = "A Minecraft Server" port = 25565 bind = "" # listen on every address, or only on this one (server-ip) max_players = 20 -online_mode = true # not supported by Horizon yet: the server runs offline and says so +online_mode = true # check players' Minecraft accounts (false: anyone joins under any name) whitelist = true # only whitelisted players and operators can join enforce_whitelist = false # kick online players taken off the whitelist view_distance = 10 diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs index 37e43df80..757b6def8 100644 --- a/crates/horizon-server/src/init.rs +++ b/crates/horizon-server/src/init.rs @@ -6,7 +6,7 @@ use crate::{config, config::Config, engine}; use horizon_server_files::{ eula, java_properties::now_millis, - user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}, + user_lists::{OpEntry, OpList, WhiteEntry, WhiteList}, }; use std::{ io::{BufRead, IsTerminal, Write}, @@ -23,6 +23,8 @@ pub struct Answers { pub whitelist: Option, pub players: Vec, pub op: Option, + /// online-mode (true unless set): players' Minecraft accounts are checked. + pub online: Option, /// Take the default for every question not answered by a flag. pub yes: bool, } @@ -30,7 +32,7 @@ pub struct Answers { impl Answers { /// The answers in the environment, for containers: `HORIZON_EULA=true`, `HORIZON_WORLD`, /// `HORIZON_SEED`, `HORIZON_PORT`, `HORIZON_WHITELIST=true|false`, `HORIZON_PLAYERS` (names separated by - /// commas) and `HORIZON_OP`. Flags given on the command line win. + /// commas), `HORIZON_OP` and `HORIZON_ONLINE=true|false`. Flags given on the command line win. pub fn from_env() -> Result { let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty()); let flag = |name: &str| var(name).map(|v| v.eq_ignore_ascii_case("true")); @@ -54,6 +56,7 @@ impl Answers { }) .unwrap_or_default(), op: var("HORIZON_OP"), + online: flag("HORIZON_ONLINE"), yes: false, }) } @@ -172,6 +175,9 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { } // 4. Who may join. + if let Some(online) = answers.online { + cfg.server.online_mode = online; + } cfg.server.whitelist = answers.whitelist.unwrap_or_else(|| { prompt.yes( "Only let in players you list (whitelist)?", @@ -193,7 +199,7 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { .yes(&format!("Make {first} an operator?"), true) .then(|| first.clone()) }); - add_players(dir, &players, op.as_deref())?; + add_players(dir, &players, op.as_deref(), cfg.server.online_mode)?; // 5. The game and its files. match engine::program(&cfg, dir) { @@ -213,24 +219,29 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { toml_path.display(), dir.display() ); - if cfg.server.online_mode { + if !cfg.server.online_mode { println!( - "Note: Horizon's server doesn't check Mojang accounts yet (online mode), so it runs offline: \ - keep the whitelist on, or play on a LAN or a tailnet." + "Note: online mode is off, so anyone can join under any name: keep the whitelist on, or play on a \ + LAN or a tailnet." ); } Ok(()) } -/// Adds players to the whitelist (and one as an operator) in vanilla's files, with offline UUIDs as the -/// server runs offline. -fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), String> { +/// Adds players to the whitelist (and one as an operator) in vanilla's files, with the profiles the server +/// will see: offline ones, or in online mode their accounts. +fn add_players( + dir: &Path, + players: &[String], + op: Option<&str>, + online: bool, +) -> Result<(), String> { if !players.is_empty() { let mut white = WhiteList::new(dir.join("whitelist.json")); let _ = white.load(); for name in players { white.add(WhiteEntry { - user: NameAndId::offline(name), + user: crate::lists::account(name, online)?, }); } println!("Whitelisted: {}", players.join(", ")); @@ -239,7 +250,7 @@ fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), S let mut ops = OpList::new(dir.join("ops.json")); let _ = ops.load(); ops.add(OpEntry { - user: NameAndId::offline(name), + user: crate::lists::account(name, online)?, level: 4, bypasses_player_limit: false, }); @@ -264,6 +275,8 @@ mod tests { whitelist: Some(true), players: vec!["Alex".into(), "Steve".into()], op: Some("Alex".into()), + // Offline: no account lookups in a test. + online: Some(false), yes: true, }; run(&dir, answers).unwrap(); @@ -277,6 +290,7 @@ mod tests { ("survival", "12345", 25599) ); assert!(eula::agreed(&dir.join("eula.txt")).unwrap()); + assert!(!cfg.server.online_mode); let white = std::fs::read_to_string(dir.join("whitelist.json")).unwrap(); assert!( white.contains("\"Alex\"") && white.contains("\"Steve\""), diff --git a/crates/horizon-server/src/lists.rs b/crates/horizon-server/src/lists.rs index 398ccfe10..a6c466666 100644 --- a/crates/horizon-server/src/lists.rs +++ b/crates/horizon-server/src/lists.rs @@ -20,7 +20,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { let message = match (command, args.as_slice()) { ("op", [name]) => { let mut ops = load(OpList::new(ops_path))?; - let user = NameAndId::offline(name); + let user = account(name, config.server.online_mode)?; if ops.contains(&user) { "Nothing changed. The player already is an operator".to_owned() } else { @@ -34,7 +34,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("deop", [name]) => { let mut ops = load(OpList::new(ops_path))?; - if ops.remove(&NameAndId::offline(name)) { + let user = listed(ops.entries().iter().map(|e| &e.user), name); + if user.is_some_and(|user| ops.remove(&user)) { format!("Made {name} no longer a server operator") } else { "Nothing changed. The player is not an operator".to_owned() @@ -42,7 +43,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("whitelist", ["add", name]) => { let mut white = load(WhiteList::new(white_path))?; - let user = NameAndId::offline(name); + let user = account(name, config.server.online_mode)?; if white.contains(&user) { "Player is already whitelisted".to_owned() } else { @@ -52,7 +53,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("whitelist", ["remove", name]) => { let mut white = load(WhiteList::new(white_path))?; - if white.remove(&NameAndId::offline(name)) { + let user = listed(white.entries().iter().map(|e| &e.user), name); + if user.is_some_and(|user| white.remove(&user)) { format!("Removed {name} from the whitelist") } else { "Player is not whitelisted".to_owned() @@ -97,6 +99,23 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { Ok(()) } +/// The profile a running server would store for `name`: the offline one, or in online mode the account the +/// services know by that name. +pub fn account(name: &str, online: bool) -> Result { + horizon_server_files::profiles::resolve(name, online).ok_or_else(|| { + if online { + format!("That player does not exist (no Minecraft account is named {name}, or the services didn't answer)") + } else { + "That player does not exist".to_owned() + } + }) +} + +/// The entry already on a list under `name` (any case), so removing needs no lookup. +fn listed<'a>(mut users: impl Iterator, name: &str) -> Option { + users.find(|u| u.name.eq_ignore_ascii_case(name)).cloned() +} + /// A list from its file; a missing file is an empty list, a broken one an error (vanilla would replace it). fn load( mut list: horizon_server_files::user_lists::UserList, diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index af45015de..c37da27a5 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -23,7 +23,7 @@ Usage: horizon-server [--dir DIR] init Set up a server here: the EULA, the world, the port, who may join (asks, or takes flags: --eula --world NAME --seed SEED --port N --whitelist/--no-whitelist --player NAME... --op NAME - --yes) + --offline --yes) run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It restarts the game if it crashes. start Run the server in the background (its output goes to logs/supervisor.log) @@ -150,6 +150,7 @@ fn init_answers(args: &[String]) -> Result { "--no-whitelist" => answers.whitelist = Some(false), "--player" => answers.players.push(value(arg)?), "--op" => answers.op = Some(value(arg)?), + "--offline" => answers.online = Some(false), other => return Err(format!("init: unknown option {other}")), } } diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py index 8e349bf0d..e6679b7b5 100644 --- a/tools/test_online_mode_parity.py +++ b/tools/test_online_mode_parity.py @@ -21,7 +21,10 @@ Also checked, with vanilla's messages: - a token the session service rejects ("Failed to log in: Invalid session"); - a join the session service forgets (the server: "Failed to verify username!"); - no account at all (the client refuses before joining); -- a verified player the whitelist refuses. +- a verified player the whitelist refuses; +- `whitelist add` in online mode: a player who joined before is known by name + and let in; another name is looked up through the services' profile lookup, + and one with no account is refused ("That player does not exist"). Horizon's dedicated server then runs the same steps in online mode (`HORIZON_API_DISCOVERY` points it at the mock too): it must give the client @@ -100,6 +103,14 @@ class Services: query = dict(urllib.parse.parse_qsl(url.query)) if url.path == '/minecraft/client': return self.reply(200, services.discovery()) + if url.path.startswith('/users/profiles/minecraft/'): + # profiles/getByName: the account with that name, ignoring case. + name = urllib.parse.unquote(url.path.rsplit('/', 1)[1]) + with services.lock: + services.log.append(('lookup', name)) + if name.lower() == PLAYER.lower(): + return self.reply(200, {'id': PLAYER_UUID, 'name': PLAYER}) + return self.reply(404, {'error': 'NOT_FOUND', 'errorMessage': f'Couldn\'t find any profile with name {name}'}) if url.path == '/session/minecraft/hasJoined': with services.lock: ok = services.joined.get(query.get('username')) == query.get('serverId') @@ -107,11 +118,15 @@ class Services: if ok: return self.reply(200, {'id': PLAYER_UUID, 'name': query['username'], 'properties': []}) return self.reply(204) + with services.lock: + services.log.append(('unknown', url.path)) self.reply(404, {'error': 'NotFound', 'path': url.path}) def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}') if self.path != '/session/minecraft/join': + with services.lock: + services.log.append(('unknown', self.path)) return self.reply(404, {'error': 'NotFound'}) token, profile, server_id = body.get('accessToken'), body.get('selectedProfile'), body.get('serverId') accepted = token in (GOOD, FORGET) and profile == PLAYER_UUID @@ -135,7 +150,8 @@ class Services: 'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined', getProfileById='/session/minecraft/profile/{profileId}'), 'player': {'endpoints': {}}, - 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}}}, + 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}, + 'getByName': {'uri': self.url + '/users/profiles/minecraft/{name}'}}}, 'telemetry': {'endpoints': {}}, }} @@ -189,8 +205,19 @@ def player_lines(lines): return out +def wait_after(server, mark, pattern, timeout=30): + """A line matching `pattern` among those the server printed after `mark`.""" + regex = re.compile(pattern) + deadline = time.time() + timeout + while time.time() < deadline: + if any(regex.search(l) for l in server.lines[mark:]): + return + time.sleep(0.2) + raise AssertionError(f'no {pattern!r} after line {mark} of {server.log_path.name}') + + def run_side(label, command, binary, build, services, discovery): - """The five logins against one server; its checks and its log about the player.""" + """The six logins against one server; its checks and its log about the player.""" port = free_port() directory = build / label shutil.rmtree(directory, ignore_errors=True) @@ -261,6 +288,24 @@ def run_side(label, command, binary, build, services, discovery): check('not whitelisted: client message', got['error'], 'disconnected: You are not white-listed on this server!') check('not whitelisted: verified first', [(e[0], e[3]) for e in services.take_log()], [('join', True), ('verify', True)]) + + # 6. Whitelisted by name: the server knows the player from their first join (its name cache), so it + # asks the services nothing, and lets them in. + mark = len(server.lines) + server.console('whitelist add tester') + wait_after(server, mark, r'Added Tester to the whitelist') + check('whitelist add: known player, no lookup', services.take_log(), []) + got = run_client(binary, build, port, f'{label}-whitelisted', GOOD, discovery) + wait_after(server, mark, r'Tester left the game') + check('whitelisted: connected throughout', got['error'], None) + services.take_log() + # A name nobody joined with: the server looks the account up, and there is none. + mark = len(server.lines) + server.console('whitelist add Nobody') + wait_after(server, mark, r'That player does not exist') + check('whitelist add: lookup failure logged', + any("Couldn't find profile with name: nobody" in l for l in server.lines[mark:]), True) + check('whitelist add: no such account', services.take_log(), [('lookup', 'nobody')]) time.sleep(1) finally: server.stop() @@ -310,7 +355,7 @@ def main(): java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], checks=len(checks), scope='Online-mode login against vanilla\'s dedicated server and Horizon\'s, with a mock session service: ' 'server hash, RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten ' - 'join, no account, whitelist; the servers\' log lines about the player.')) + 'join, no account, whitelist, whitelist add by account name; the servers\' log lines about the player.')) print(f'online mode: {len(checks)} checks ok') From 78791b79ceb6c7c7dc6f1fa4b02e2d6e91f2f3d4 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:03:14 +0100 Subject: [PATCH 007/327] Cache resolved block behaviours across launches --- Cargo.lock | 57 ++ crates/horizon-world/Cargo.toml | 3 + .../examples/behaviour_load_profile.rs | 27 + crates/horizon-world/src/level/data.rs | 17 +- crates/horizon-world/src/level/data/cache.rs | 810 ++++++++++++++++++ tools/profile_client_startup.py | 49 ++ 6 files changed, 960 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-world/examples/behaviour_load_profile.rs create mode 100644 crates/horizon-world/src/level/data/cache.rs create mode 100644 tools/profile_client_startup.py diff --git a/Cargo.lock b/Cargo.lock index 1d5897d11..9726316b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -196,6 +196,15 @@ dependencies = [ "libloading", ] +[[package]] +name = "atomic-polyfill" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" +dependencies = [ + "critical-section", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -322,6 +331,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -742,6 +757,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1307,6 +1328,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hash32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" +dependencies = [ + "byteorder", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -1337,6 +1367,20 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "heapless" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" +dependencies = [ + "atomic-polyfill", + "hash32", + "rustc_version", + "serde", + "spin", + "stable_deref_trait", +] + [[package]] name = "heck" version = "0.5.0" @@ -1608,7 +1652,10 @@ dependencies = [ "horizon-core", "libm", "lz4_flex", + "postcard", + "serde", "serde_json", + "sha2", "xxhash-rust", ] @@ -2872,6 +2919,7 @@ dependencies = [ "cobs", "embedded-io 0.4.0", "embedded-io 0.6.1", + "heapless", "serde", ] @@ -3458,6 +3506,15 @@ dependencies = [ "sha2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + [[package]] name = "spirv" version = "0.4.0+sdk-1.4.341.0" diff --git a/crates/horizon-world/Cargo.toml b/crates/horizon-world/Cargo.toml index 078692bff..3e5f9466d 100644 --- a/crates/horizon-world/Cargo.toml +++ b/crates/horizon-world/Cargo.toml @@ -9,6 +9,9 @@ description = "Horizon vanilla world data, NBT, regions and chunk storage" [dependencies] libm = "=0.2.16" serde_json = { version = "1.0.151", features = ["raw_value"] } +serde = { version = "1", features = ["derive"] } +sha2 = "0.10" +postcard = { version = "=1.1.3", features = ["alloc"] } horizon-core = { path = "../horizon-core" } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } lz4_flex = { version = "0.14", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] } diff --git a/crates/horizon-world/examples/behaviour_load_profile.rs b/crates/horizon-world/examples/behaviour_load_profile.rs new file mode 100644 index 000000000..e6619afa1 --- /dev/null +++ b/crates/horizon-world/examples/behaviour_load_profile.rs @@ -0,0 +1,27 @@ +//! Measure registry and behaviour load times using prepared client resources. +use horizon_world::level::{Behaviours, data::load_registry}; +use std::{path::Path, time::Instant}; + +fn main() -> Result<(), Box> { + let root = std::env::args() + .nth(1) + .expect("resource directory argument"); + let root = Path::new(&root); + let started = Instant::now(); + let registry = load_registry(root)?; + eprintln!( + "registry_ms={:.3}", + started.elapsed().as_secs_f64() * 1000.0 + ); + for iteration in 0..3 { + let started = Instant::now(); + let behaviours = Behaviours::load(®istry, root)?; + eprintln!( + "behaviours_{}_ms={:.3}", + iteration, + started.elapsed().as_secs_f64() * 1000.0 + ); + std::hint::black_box(behaviours); + } + Ok(()) +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 455a2ed57..83349232c 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -21,6 +21,8 @@ use std::{ path::Path, sync::Arc, }; +#[path = "data/cache.rs"] +mod cache; /// Per-state flags read from vanilla accessors over an empty level. pub mod state_flags { @@ -251,7 +253,7 @@ macro_rules! named_blocks { #[derive(Clone, Copy, Debug)] pub struct Named { $(pub $field: BlockId,)* } impl Named { - fn resolve(table: &StateTable) -> io::Result { + pub(super) fn resolve(table: &StateTable) -> io::Result { Ok(Self { $($field: table.block_by_name(concat!("minecraft:", $name)).ok_or_else(|| invalid(concat!("missing block ", $name)))?,)* }) } } @@ -393,7 +395,7 @@ macro_rules! tags { #[derive(Clone, Debug, Default)] pub struct Tags { $(pub $field: Arc,)* } impl Tags { - fn resolve(all: &HashMap>) -> Self { + pub(super) fn resolve(all: &HashMap>) -> Self { Self { $($field: all.get(concat!("minecraft:", $name)).cloned().unwrap_or_default(),)* } } } @@ -487,7 +489,7 @@ macro_rules! props { #[derive(Clone, Copy, Debug)] pub struct Props { $(pub $field: PropKey,)* } impl Props { - fn resolve(table: &mut StateTable) -> Self { + pub(super) fn resolve(table: &mut StateTable) -> Self { Self { $($field: table.key($name),)* } } } @@ -653,6 +655,15 @@ pub fn load_registry(root: &Path) -> io::Result { } pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result { + if let Some(behaviours) = cache::load(registry, root) { + return Ok(behaviours); + } + let behaviours = load_uncached(registry, root)?; + cache::store(registry, root, &behaviours); + Ok(behaviours) +} + +fn load_uncached(registry: &BlockRegistry, root: &Path) -> io::Result { let mut table = StateTable::new(registry)?; let props = Props::resolve(&mut table); let named = Named::resolve(&table)?; diff --git a/crates/horizon-world/src/level/data/cache.rs b/crates/horizon-world/src/level/data/cache.rs new file mode 100644 index 000000000..3a18a7131 --- /dev/null +++ b/crates/horizon-world/src/level/data/cache.rs @@ -0,0 +1,810 @@ +//! A disposable, versioned snapshot of resolved behaviour tables. +//! +//! The source resources remain authoritative. Failed reads, unsupported +//! versions, corrupt payloads and write failures always use the normal loader. +use super::*; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + io::Write, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, +}; + +const MAGIC: &[u8; 8] = b"HZBEHAV\0"; +const VERSION: u32 = 2; +const FILE_NAME: &str = ".horizon-behaviours-v2.bin"; +const MAX_FILE_BYTES: usize = 128 * 1024 * 1024; +const MAX_DECODED_BYTES: usize = 256 * 1024 * 1024; +static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + +#[derive(Serialize, Deserialize)] +struct Snapshot { + tags: HashMap>, + facts: Vec, + shapes: Vec, + shape_info: Vec<[u8; 3]>, + fluid_tags: [u8; 6], + blocks: Vec, + items: HashMap, +} + +#[derive(Serialize, Deserialize)] +struct Fact { + flags: u32, + sturdy: u32, + weak: u32, + strong: u32, + fluid_kind: u8, + fluid_amount: u8, + fluid_falling: bool, + emission: u8, + dampening: u8, + hardness: f32, + push: u8, + instrument: u8, + shape: i32, +} + +#[derive(Serialize, Deserialize)] +struct Shape { + coords: [Vec; 3], + occupied: Vec, + cube: bool, + coordinate_cubes: [bool; 3], + min: [i32; 3], + max: [i32; 3], + /// Preserve the shared singleton identities used by vanilla shape shortcuts. + singleton: u8, +} + +#[derive(Serialize, Deserialize)] +struct SetTypeSnapshot { + name: String, + can_open_by_hand: bool, + can_open_by_wind_charge: bool, + arrows: bool, + mobs_only: bool, + door_open: String, + door_close: String, + trapdoor_open: String, + trapdoor_close: String, + plate_on: String, + plate_off: String, + button_on: String, + button_off: String, +} + +#[derive(Serialize, Deserialize)] +struct SoundsSnapshot { + volume: f32, + pitch: f32, + place: String, + break_: String, + fall: String, +} + +#[derive(Serialize, Deserialize)] +struct Block { + chain: Vec, + interfaces: u16, + set_type: Option, + gate_open: Option, + gate_close: Option, + open_sound: Option, + close_sound: Option, + ticks_to_stay_pressed: i32, + max_weight: i32, + link: Option, + link2: Option, + support_tag: Option>, + support_tag2: Option>, + feature: Option, + grow_probability: f64, + growth_direction: u8, + schedule_fluid_ticks: bool, + weather: u8, + ignite_odds: i32, + burn_odds: i32, + sounds: SoundsSnapshot, + item: String, + dynamic_shape: bool, +} + +#[derive(Serialize, Deserialize)] +struct Item { + block: u16, + wall_block: Option, + attachment: Option, + kind: u8, + game_master: bool, +} + +fn fingerprint(registry: &BlockRegistry, root: &Path) -> io::Result<[u8; 32]> { + let mut hasher = Sha256::new(); + hasher.update(b"horizon resolved behaviours 2"); + for relative in [ + "facts.json", + "block-behaviours.json", + "gameplay-facts.json", + "block-tags.json", + "cached-collision.nbt", + ] { + hash_file(&mut hasher, root, &root.join(relative))?; + } + let mut fluids: Vec = fs::read_dir(root.join("data/minecraft/tags/fluid"))? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>()?; + fluids.sort(); + for path in fluids { + hash_file(&mut hasher, root, &path)?; + } + // The registry argument may be modified independently of facts.json. + hasher.update((registry.len() as u64).to_le_bytes()); + let mut seen = std::collections::HashSet::new(); + for index in 0..registry.len() { + let state = registry + .state(BlockStateId(index as u32)) + .ok_or_else(|| invalid("missing registry state"))?; + hash_str(&mut hasher, &state.name); + let mut props: Vec<_> = state.properties.iter().collect(); + props.sort_by_key(|(key, _)| *key); + hasher.update((props.len() as u32).to_le_bytes()); + for (key, value) in props { + hash_str(&mut hasher, key); + hash_str(&mut hasher, value); + } + if seen.insert(state.name.as_str()) { + let default = registry + .default_state(&state.name) + .ok_or_else(|| invalid("missing default state"))?; + hasher.update(default.0.to_le_bytes()); + } + } + Ok(hasher.finalize().into()) +} + +fn hash_str(hasher: &mut Sha256, text: &str) { + hasher.update((text.len() as u64).to_le_bytes()); + hasher.update(text.as_bytes()); +} + +fn hash_file(hasher: &mut Sha256, root: &Path, path: &Path) -> io::Result<()> { + let relative = path + .strip_prefix(root) + .map_err(|e| invalid(e.to_string()))?; + hash_str(hasher, &relative.to_string_lossy()); + let bytes = fs::read(path)?; + hasher.update((bytes.len() as u64).to_le_bytes()); + hasher.update(bytes); + Ok(()) +} + +fn direction(index: u8) -> io::Result { + Direction::ALL + .get(index as usize) + .copied() + .ok_or_else(|| invalid("cached direction out of range")) +} +fn direction_index(direction: Direction) -> u8 { + Direction::ALL.iter().position(|d| *d == direction).unwrap() as u8 +} +fn class(index: u16) -> io::Result { + Class::ALL + .get(index as usize) + .copied() + .ok_or_else(|| invalid("cached block class out of range")) +} +fn kind(index: u8) -> io::Result { + Ok(match index { + 0 => ItemKind::Block, + 1 => ItemKind::DoubleHigh, + 2 => ItemKind::StandingAndWall, + 3 => ItemKind::Scaffolding, + 4 => ItemKind::PlaceOnWater, + 5 => ItemKind::HangingSign, + 6 => ItemKind::SolidBucket, + 7 => ItemKind::Other, + _ => return Err(invalid("cached item kind out of range")), + }) +} +fn kind_index(kind: ItemKind) -> u8 { + match kind { + ItemKind::Block => 0, + ItemKind::DoubleHigh => 1, + ItemKind::StandingAndWall => 2, + ItemKind::Scaffolding => 3, + ItemKind::PlaceOnWater => 4, + ItemKind::HangingSign => 5, + ItemKind::SolidBucket => 6, + ItemKind::Other => 7, + } +} +fn push(index: u8) -> io::Result { + Ok(match index { + 0 => PushReaction::PushPull, + 1 => PushReaction::Push, + 2 => PushReaction::Popped, + 3 => PushReaction::Immoveable, + 4 => PushReaction::IgnoreEntity, + _ => return Err(invalid("cached push reaction out of range")), + }) +} +fn push_index(push: PushReaction) -> u8 { + match push { + PushReaction::PushPull => 0, + PushReaction::Push => 1, + PushReaction::Popped => 2, + PushReaction::Immoveable => 3, + PushReaction::IgnoreEntity => 4, + } +} + +impl From<&SetType> for SetTypeSnapshot { + fn from(value: &SetType) -> Self { + Self { + name: value.name.to_string(), + can_open_by_hand: value.can_open_by_hand, + can_open_by_wind_charge: value.can_open_by_wind_charge, + arrows: value.arrows, + mobs_only: value.mobs_only, + door_open: value.door_open.to_string(), + door_close: value.door_close.to_string(), + trapdoor_open: value.trapdoor_open.to_string(), + trapdoor_close: value.trapdoor_close.to_string(), + plate_on: value.plate_on.to_string(), + plate_off: value.plate_off.to_string(), + button_on: value.button_on.to_string(), + button_off: value.button_off.to_string(), + } + } +} +impl From for SetType { + fn from(value: SetTypeSnapshot) -> Self { + Self { + name: value.name.into(), + can_open_by_hand: value.can_open_by_hand, + can_open_by_wind_charge: value.can_open_by_wind_charge, + arrows: value.arrows, + mobs_only: value.mobs_only, + door_open: Arc::from(value.door_open), + door_close: Arc::from(value.door_close), + trapdoor_open: Arc::from(value.trapdoor_open), + trapdoor_close: Arc::from(value.trapdoor_close), + plate_on: Arc::from(value.plate_on), + plate_off: Arc::from(value.plate_off), + button_on: Arc::from(value.button_on), + button_off: Arc::from(value.button_off), + } + } +} +impl From<&Sounds> for SoundsSnapshot { + fn from(value: &Sounds) -> Self { + Self { + volume: value.volume, + pitch: value.pitch, + place: value.place.to_string(), + break_: value.break_.to_string(), + fall: value.fall.to_string(), + } + } +} +impl From for Sounds { + fn from(value: SoundsSnapshot) -> Self { + Self { + volume: value.volume, + pitch: value.pitch, + place: Arc::from(value.place), + break_: Arc::from(value.break_), + fall: Arc::from(value.fall), + } + } +} + +impl Snapshot { + fn capture(behaviours: &Behaviours) -> Self { + let tags = behaviours + .all_tags + .iter() + .map(|(key, value)| (key.clone(), value.0.clone())) + .collect(); + let facts = behaviours + .facts + .iter() + .map(|fact| Fact { + flags: fact.flags, + sturdy: fact.sturdy, + weak: fact.weak, + strong: fact.strong, + fluid_kind: fact.fluid.kind() as u8, + fluid_amount: fact.fluid.amount(), + fluid_falling: fact.fluid.falling(), + emission: fact.emission, + dampening: fact.dampening, + hardness: fact.hardness, + push: push_index(fact.push), + instrument: fact.instrument, + shape: fact.shape, + }) + .collect(); + let shapes = behaviours + .shapes + .iter() + .map(|shape| { + let sizes = shape.sizes(); + let mut occupied = Vec::with_capacity(sizes.iter().product()); + for x in 0..sizes[0] { + for y in 0..sizes[1] { + for z in 0..sizes[2] { + occupied.push(shape.is_full(x as i32, y as i32, z as i32)); + } + } + } + let (min, max) = shape.discrete_bounds(); + Shape { + coords: std::array::from_fn(|axis| { + shape + .coordinates( + [ + horizon_core::geometry::Axis::X, + horizon_core::geometry::Axis::Y, + horizon_core::geometry::Axis::Z, + ][axis], + ) + .to_vec() + }), + occupied, + cube: shape.is_cube(), + coordinate_cubes: shape.cube_coordinate_axes(), + min, + max, + singleton: if shape.same_identity(&VoxelShape::block()) { + 1 + } else if shape.same_identity(&VoxelShape::empty()) { + 2 + } else { + 0 + }, + } + }) + .collect(); + let shape_info = behaviours + .shape_info + .iter() + .map(|info| [info.full_faces, info.nonempty_faces, info.wall_cover]) + .collect(); + let tags = tags; + let f = behaviours.fluid_tags; + let fluid_tags = [ + f.water, + f.lava, + f.supports_frogspawn, + f.supports_lily_pad, + f.supports_sugar_cane_adjacently, + f.bubble_column_can_occupy, + ]; + let blocks = behaviours + .blocks + .iter() + .map(|block| Block { + chain: block.chain.iter().map(|class| *class as u16).collect(), + interfaces: block.interfaces, + set_type: block + .set_type + .as_ref() + .map(|value| SetTypeSnapshot::from(value.as_ref())), + gate_open: block.gate_open.as_ref().map(|v| v.to_string()), + gate_close: block.gate_close.as_ref().map(|v| v.to_string()), + open_sound: block.open_sound.as_ref().map(|v| v.to_string()), + close_sound: block.close_sound.as_ref().map(|v| v.to_string()), + ticks_to_stay_pressed: block.ticks_to_stay_pressed, + max_weight: block.max_weight, + link: block.link.map(|v| v.0), + link2: block.link2.map(|v| v.0), + support_tag: block.support_tag.as_ref().map(|v| v.0.clone()), + support_tag2: block.support_tag2.as_ref().map(|v| v.0.clone()), + feature: block.feature.as_ref().map(|v| v.to_string()), + grow_probability: block.grow_probability, + growth_direction: direction_index(block.growth_direction), + schedule_fluid_ticks: block.schedule_fluid_ticks, + weather: block.weather, + ignite_odds: block.ignite_odds, + burn_odds: block.burn_odds, + sounds: SoundsSnapshot::from(block.sounds.as_ref()), + item: block.item.to_string(), + dynamic_shape: block.dynamic_shape, + }) + .collect(); + let items = behaviours + .items + .iter() + .map(|(name, item)| { + ( + name.clone(), + Item { + block: item.block.0, + wall_block: item.wall_block.map(|v| v.0), + attachment: item.attachment.map(direction_index), + kind: kind_index(item.kind), + game_master: item.game_master, + }, + ) + }) + .collect(); + Self { + tags, + facts, + shapes, + shape_info, + fluid_tags, + blocks, + items, + } + } + + fn restore(self, registry: &BlockRegistry) -> io::Result { + let mut table = StateTable::new(registry)?; + let props = Props::resolve(&mut table); + let named = Named::resolve(&table)?; + if self.facts.len() != table.state_count() + || self.blocks.len() != table.block_count() + || self.shape_info.len() != self.shapes.len() + { + return Err(invalid("cached behaviour table size mismatch")); + } + let all_tags: HashMap> = self + .tags + .into_iter() + .map(|(key, value)| (key, Arc::new(BlockSet(value)))) + .collect(); + let tags = Tags::resolve(&all_tags); + let shapes = self + .shapes + .into_iter() + .map(|wire| { + let shape = match wire.singleton { + 1 => VoxelShape::block(), + 2 => VoxelShape::empty(), + 0 => { + if wire.cube { + let sizes = std::array::from_fn(|axis| { + wire.coords[axis].len().saturating_sub(1) + }); + VoxelShape::from_cube(sizes, &wire.occupied) + .map_err(|e| invalid(e.to_string()))? + } else { + VoxelShape::from_mixed_grid( + wire.coords, + &wire.occupied, + wire.coordinate_cubes, + ) + .map_err(|e| invalid(e.to_string()))? + } + } + _ => return Err(invalid("invalid cached shape identity")), + }; + shape + .with_discrete_bounds(wire.min, wire.max) + .map_err(|e| invalid(e.to_string())) + }) + .collect::>>()?; + let shape_info = self + .shape_info + .into_iter() + .map(|row| ShapeInfo { + full_faces: row[0], + nonempty_faces: row[1], + wall_cover: row[2], + }) + .collect(); + let facts = self + .facts + .into_iter() + .map(|wire| { + if wire.shape < -1 || wire.shape >= shapes.len() as i32 { + return Err(invalid("cached shape index out of range")); + } + let fluid_kind = FluidKind::ALL + .get(wire.fluid_kind as usize) + .copied() + .ok_or_else(|| invalid("cached fluid kind out of range"))?; + Ok(StateFacts { + flags: wire.flags, + sturdy: wire.sturdy, + weak: wire.weak, + strong: wire.strong, + fluid: FluidState::new(fluid_kind, wire.fluid_amount, wire.fluid_falling), + emission: wire.emission, + dampening: wire.dampening, + hardness: wire.hardness, + push: push(wire.push)?, + instrument: wire.instrument, + shape: wire.shape, + }) + }) + .collect::>>()?; + let f = self.fluid_tags; + let fluid_tags = FluidTags { + water: f[0], + lava: f[1], + supports_frogspawn: f[2], + supports_lily_pad: f[3], + supports_sugar_cane_adjacently: f[4], + bubble_column_can_occupy: f[5], + }; + let blocks = self + .blocks + .into_iter() + .map(|wire| { + let chain = wire + .chain + .into_iter() + .map(class) + .collect::>>()?; + let mut classes = ClassSet::default(); + for class in &chain { + classes.insert(*class); + } + let class = chain.first().copied().unwrap_or(Class::Block); + for link in [wire.link, wire.link2].into_iter().flatten() { + if link as usize >= table.block_count() { + return Err(invalid("cached block link out of range")); + } + } + Ok(BlockData { + class, + chain, + classes, + interfaces: wire.interfaces, + set_type: wire.set_type.map(|v| Arc::new(SetType::from(v))), + gate_open: wire.gate_open.map(Arc::from), + gate_close: wire.gate_close.map(Arc::from), + open_sound: wire.open_sound.map(Arc::from), + close_sound: wire.close_sound.map(Arc::from), + ticks_to_stay_pressed: wire.ticks_to_stay_pressed, + max_weight: wire.max_weight, + link: wire.link.map(BlockId), + link2: wire.link2.map(BlockId), + support_tag: wire.support_tag.map(|v| Arc::new(BlockSet(v))), + support_tag2: wire.support_tag2.map(|v| Arc::new(BlockSet(v))), + feature: wire.feature.map(Arc::from), + grow_probability: wire.grow_probability, + growth_direction: direction(wire.growth_direction)?, + schedule_fluid_ticks: wire.schedule_fluid_ticks, + weather: wire.weather, + ignite_odds: wire.ignite_odds, + burn_odds: wire.burn_odds, + sounds: Arc::new(Sounds::from(wire.sounds)), + item: Arc::from(wire.item), + dynamic_shape: wire.dynamic_shape, + }) + }) + .collect::>>()?; + let items = self + .items + .into_iter() + .map(|(name, wire)| { + if wire.block as usize >= table.block_count() + || wire + .wall_block + .is_some_and(|id| id as usize >= table.block_count()) + { + return Err(invalid("cached item block out of range")); + } + Ok(( + name, + ItemBinding { + block: BlockId(wire.block), + wall_block: wire.wall_block.map(BlockId), + attachment: wire.attachment.map(direction).transpose()?, + kind: kind(wire.kind)?, + game_master: wire.game_master, + }, + )) + }) + .collect::>>()?; + let liquid_blocks = FluidBlockBindings::new(registry)?; + let mut dynamic = HashMap::new(); + for (id, fact) in facts.iter().enumerate() { + if fact.shape < 0 { + let state = BlockStateId(id as u32); + if let Some(support) = crate::dynamic_support::DynamicSupport::from_state( + registry.state(state).unwrap(), + )? { + dynamic.insert(state, support); + } + } + } + Ok(Behaviours { + table, + props, + named, + tags, + all_tags, + facts, + shapes, + shape_info, + fluid_tags, + blocks, + items, + liquid_blocks, + dynamic, + occlusion_cache: Default::default(), + growth: Default::default(), + }) + } +} + +pub(super) fn load(registry: &BlockRegistry, root: &Path) -> Option { + let fingerprint = fingerprint(registry, root).ok()?; + let bytes = fs::read(root.join(FILE_NAME)).ok()?; + // Validate bounds before decoding untrusted cache contents. + if bytes.len() < 8 + 4 + 32 + 32 || bytes.len() > MAX_FILE_BYTES { + return None; + } + if &bytes[..8] != MAGIC + || u32::from_le_bytes(bytes[8..12].try_into().ok()?) != VERSION + || bytes[12..44] != fingerprint + { + return None; + } + let body = &bytes[76..]; + if Sha256::digest(body).as_slice() != &bytes[44..76] { + return None; + } + let expanded_len = u32::from_le_bytes(body.get(..4)?.try_into().ok()?) as usize; + if expanded_len > MAX_DECODED_BYTES { + return None; + } + let expanded = lz4_flex::decompress_size_prepended(body).ok()?; + let snapshot: Snapshot = postcard::from_bytes(&expanded).ok()?; + snapshot.restore(registry).ok() +} + +pub(super) fn store(registry: &BlockRegistry, root: &Path, behaviours: &Behaviours) { + let _ = write(registry, root, behaviours); +} + +fn write(registry: &BlockRegistry, root: &Path, behaviours: &Behaviours) -> io::Result<()> { + let fingerprint = fingerprint(registry, root)?; + let snapshot = Snapshot::capture(behaviours); + let serialized = postcard::to_allocvec(&snapshot).map_err(|e| invalid(e.to_string()))?; + let body = lz4_flex::compress_prepend_size(&serialized); + if body.len() + 76 > MAX_FILE_BYTES { + return Err(invalid("behaviour cache too large")); + } + let mut bytes = Vec::with_capacity(76 + body.len()); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&VERSION.to_le_bytes()); + bytes.extend_from_slice(&fingerprint); + bytes.extend_from_slice(&Sha256::digest(&body)); + bytes.extend_from_slice(&body); + let path = root.join(FILE_NAME); + let tmp = root.join(format!( + "{FILE_NAME}.tmp-{}-{}", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + let result = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp)?; + file.write_all(&bytes)?; + file.sync_all()?; + fs::rename(&tmp, &path) + })(); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicU64; + + static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + + struct FixtureDir(PathBuf); + impl Drop for FixtureDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn fixture() -> Option { + let source = std::env::var_os("HORIZON_RESOURCES") + .map(PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !source.join("block-behaviours.json").exists() { + eprintln!("skipping behaviour cache tests: no client resources"); + return None; + } + let dir = std::env::temp_dir().join(format!( + "horizon-behaviour-cache-test-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir_all(dir.join("data/minecraft/tags/fluid")).unwrap(); + for file in [ + "facts.json", + "block-behaviours.json", + "gameplay-facts.json", + "block-tags.json", + "cached-collision.nbt", + ] { + fs::copy(source.join(file), dir.join(file)).unwrap(); + } + for entry in fs::read_dir(source.join("data/minecraft/tags/fluid")).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_file() { + fs::copy( + entry.path(), + dir.join("data/minecraft/tags/fluid") + .join(entry.file_name()), + ) + .unwrap(); + } + } + Some(FixtureDir(dir)) + } + + #[test] + fn resolved_snapshot_roundtrips_all_fields() { + let Some(root) = fixture() else { + return; + }; + let registry = super::super::load_registry(&root.0).unwrap(); + let original = super::super::load_uncached(®istry, &root.0).unwrap(); + let captured = Snapshot::capture(&original); + let restored = captured.restore(®istry).unwrap(); + assert_eq!( + serde_json::to_value(Snapshot::capture(&original)).unwrap(), + serde_json::to_value(Snapshot::capture(&restored)).unwrap(), + "all resolved fields, shape grids and identities should roundtrip", + ); + } + + #[test] + fn cache_invalidates_sources_and_recovers_from_corruption() { + let Some(root) = fixture() else { + return; + }; + let registry = super::super::load_registry(&root.0).unwrap(); + assert!(load(®istry, &root.0).is_none()); + let initial = super::super::load(®istry, &root.0).unwrap(); + assert!(root.0.join(FILE_NAME).is_file()); + let hit = load(®istry, &root.0).expect("cache hit"); + assert_eq!(initial.table.state_count(), hit.table.state_count()); + let tags = root.0.join("block-tags.json"); + fs::OpenOptions::new() + .append(true) + .open(&tags) + .unwrap() + .write_all(b"\n") + .unwrap(); + assert!( + load(®istry, &root.0).is_none(), + "changed resource must invalidate" + ); + super::super::load(®istry, &root.0).expect("source fallback"); + assert!( + load(®istry, &root.0).is_some(), + "fallback should replace cache" + ); + let cache_file = root.0.join(FILE_NAME); + let mut bytes = fs::read(&cache_file).unwrap(); + bytes[80] ^= 0x80; + fs::write(&cache_file, bytes).unwrap(); + assert!( + load(®istry, &root.0).is_none(), + "checksum failure must invalidate" + ); + super::super::load(®istry, &root.0).expect("corrupt cache fallback"); + assert!(load(®istry, &root.0).is_some()); + } +} diff --git a/tools/profile_client_startup.py b/tools/profile_client_startup.py new file mode 100644 index 000000000..76ad9002c --- /dev/null +++ b/tools/profile_client_startup.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Measure the resource-dependent Behaviours::load portion of client startup. + +Build the behaviour_load_profile example in the checkout to be measured first: + cargo build --release -p horizon-world --example behaviour_load_profile + +Run the profiler from the repository root with the matching example binary. +This measures behaviour loading, not time to first rendered frame. +""" +import argparse +import json +import re +import statistics +import subprocess +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, default=Path("target/release/examples/behaviour_load_profile")) + parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3")) + parser.add_argument("--repeats", type=int, default=5) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + if args.repeats < 1: + parser.error("--repeats must be at least one") + samples = [] + for _ in range(args.repeats): + run = subprocess.run([str(args.binary.resolve()), str(args.resources.resolve())], + text=True, capture_output=True, check=True) + values = {key: float(value) for key, value in + re.findall(r"^(registry_ms|behaviours_[0-2]_ms)=([\d.]+)$", run.stderr, re.M)} + if len(values) != 4: + raise RuntimeError(f"incomplete profile output: {run.stderr}") + samples.append(values) + summary = {key: {"median_ms": round(statistics.median(row[key] for row in samples), 3), + "samples_ms": [row[key] for row in samples]} + for key in samples[0]} + result = {"scope": "behaviour loader only; not full client startup", + "binary": str(args.binary), "resources": str(args.resources), "repeats": args.repeats, + "metrics": summary} + print(json.dumps(result, indent=2)) + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n") + + +if __name__ == "__main__": + main() From 1d3759bb77dd7e9e6d08c689834001fbee4b3929 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 02:40:33 +0200 Subject: [PATCH 008/327] Drop a redundant binding flagged by clippy Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/src/level/data/cache.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/horizon-world/src/level/data/cache.rs b/crates/horizon-world/src/level/data/cache.rs index 3a18a7131..f143cf6cd 100644 --- a/crates/horizon-world/src/level/data/cache.rs +++ b/crates/horizon-world/src/level/data/cache.rs @@ -373,7 +373,6 @@ impl Snapshot { .iter() .map(|info| [info.full_faces, info.nonempty_faces, info.wall_cover]) .collect(); - let tags = tags; let f = behaviours.fluid_tags; let fluid_tags = [ f.water, From 943dd210d7369ba75456d4df7b76e6fd76f41126 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 02:59:37 +0200 Subject: [PATCH 009/327] Dedicated server: encode each chunk section once, not once per player Chunk packets took nearly all of the server's tick with players moving about: every send re-encoded the column for that player (each section unpacked and re-paletted with linear searches, light layers packed a nibble at a time, heightmaps primed again) and unpacked all 9 x 24 sections around it to find which light layers exist. At 50 walking bots that was ~85 % of the tick, 280-470 ms ticks against vanilla's 33 ms on the benchmark machine. The encoder now keeps what a resident section gives the wire (its bytes, whether it holds block entity blocks, whether it is all air) by the section's address. Sections are immutable behind Arc and edits go through Arc::make_mut, so an edited section moves to a new address, and the cache's Weak keeps an old address from being reused: the same address is the same unchanged section. Heightmaps are kept per column the same way. Block entity tags are still read for every packet. The bytes sent don't change. Also: Paletted::from_values uses an index table instead of linear palette searches (the same palette order and bits), the all-air check reads the palette first and stops at the first block, uniform sections skip unpacking, and light layers pack two blocks per byte in one pass. On a busy Mac mini with 50 walking bots (`tick query`): about 400 ms ticks with the faster palette and air checks alone, 14 ms with the caches. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/chunks.rs | 241 ++++++++++++++++++++---- crates/horizon-protocol/src/chunk.rs | 84 +++++++++ 2 files changed, 289 insertions(+), 36 deletions(-) diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 6ca321edd..71e0c889b 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -90,7 +90,32 @@ pub struct ChunkEncoder { pub block_ids: Vec, /// The save's tables, for the heightmaps. pub tables: Option>, + /// Sections already looked at, by address (see `Encoded`). + cache: std::sync::Mutex>, + /// Each column's heightmaps, with the sections they were made from. + heights: std::sync::Mutex>, } + +/// A column's client heightmaps, valid while it holds the same sections. +struct Heights { + sections: Vec>, + maps: Vec<(i32, Vec)>, +} + +/// What a resident section gives the wire, kept while the section is +/// unchanged. Resident sections are immutable behind `Arc` (edits go through +/// `Arc::make_mut`, which moves an edited section to a new address while a +/// `Weak` points at the old one), and the `Weak` keeps the old address from +/// being reused: the same address is the same, unchanged section. +struct Encoded { + section: std::sync::Weak
, + non_air: bool, + /// LevelChunkSection.write, and whether it holds block entity blocks. + wire: Option<(Arc<[u8]>, bool)>, +} + +/// Sections kept before the ones no longer resident are dropped. +const CACHE_SWEEP: usize = 1 << 15; impl ChunkEncoder { /// `biome_names`: the internal biome list in order; `biome_registry`: /// the synchronized biome entries in network order. @@ -143,8 +168,89 @@ impl ChunkEncoder { biome_bits: ceil_log2(biome_registry.len()), block_ids, tables: None, + cache: Default::default(), + heights: Default::default(), } } + + /// The client heightmaps (Heightmap.prime over the column), from the + /// cache while the column's sections are unchanged. + fn heightmaps(&self, chunk: &Chunk, tables: &crate::save::SaveTables) -> Vec<(i32, Vec)> { + let same = |h: &Heights| { + h.sections.len() == chunk.sections.len() + && h.sections + .iter() + .zip(&chunk.sections) + .all(|(w, s)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(s))) + }; + let mut heights = self.heights.lock().unwrap(); + if let Some(h) = heights.get(&(chunk.x, chunk.z)) + && same(h) + { + return h.maps.clone(); + } + if heights.len() >= CACHE_SWEEP / 4 { + heights.retain(|_, h| h.sections.iter().all(|w| w.strong_count() > 0)); + if heights.len() >= CACHE_SWEEP / 8 { + heights.clear(); + } + } + let maps = crate::save::client_heightmaps(chunk, tables); + heights.insert( + (chunk.x, chunk.z), + Heights { + sections: chunk.sections.iter().map(Arc::downgrade).collect(), + maps: maps.clone(), + }, + ); + maps + } + + /// The cached entry for a section, made with `non_air` when missing. + fn cached(&self, section: &Arc
, read: impl FnOnce(&mut Encoded) -> T) -> T { + let mut cache = self.cache.lock().unwrap(); + if cache.len() >= CACHE_SWEEP { + cache.retain(|_, e| e.section.strong_count() > 0); + if cache.len() >= CACHE_SWEEP / 2 { + cache.clear(); + } + } + let entry = cache + .entry(Arc::as_ptr(section) as usize) + .or_insert_with(|| Encoded { + section: Arc::downgrade(section), + non_air: self.non_air(section), + wire: None, + }); + read(entry) + } + + /// LevelChunkSection.hasOnlyAir, negated. + fn non_air(&self, section: &Section) -> bool { + let non_air = |v: u32| self.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; + // The palette first: most sections are all air, or one block. + if !section.blocks.maybe_has(non_air) { + false + } else if let Some(v) = section.blocks.uniform() { + non_air(v) + } else { + // Stops at the first block, usually near the bottom. + (0..BLOCKS).any(|i| non_air(section.blocks.get(i))) + } + } + + /// A section on the wire, from the cache or encoded now. + fn section_wire(&self, section: &Arc
) -> (Arc<[u8]>, bool) { + if let Some(wire) = self.cached(section, |e| e.wire.clone()) { + return wire; + } + let (encoded, entities) = self.section(section); + let mut w = horizon_protocol::buf::Writer::new(); + encoded.write(&mut w); + let wire: (Arc<[u8]>, bool) = (w.data.into(), entities); + self.cached(section, |e| e.wire = Some(wire.clone())); + wire + } pub fn entity_type(&self, state: u16) -> Option { self.entity_types .get(usize::from(state)) @@ -170,11 +276,17 @@ impl ChunkEncoder { } f & ENTITY != 0 }; - let mut unpacked = [0u16; BLOCKS]; - section.unpack(&mut unpacked); - for &v in &unpacked { - entities |= count(v, 1); - values.push(i32::from(v)); + // One block everywhere (all air, mostly): what from_values would give. + let uniform = section.blocks.uniform(); + if let Some(v) = uniform { + entities = count(v as u16, BLOCKS as i16); + } else { + let mut unpacked = [0u16; BLOCKS]; + section.unpack(&mut unpacked); + for &v in &unpacked { + entities |= count(v, 1); + values.push(i32::from(v)); + } } let biome_values: Vec = (0..BIOMES) .map(|j| { @@ -189,7 +301,14 @@ impl ChunkEncoder { horizon_protocol::chunk::Section { non_empty, fluids, - states: Paletted::from_values(&values, Strategy::Blocks, 16), + states: match uniform { + Some(v) => Paletted { + bits: 0, + palette: vec![v as i32], + data: Vec::new(), + }, + None => Paletted::from_values(&values, Strategy::Blocks, 16), + }, biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), }, entities, @@ -201,12 +320,7 @@ impl ChunkEncoder { fn occupied(&self, chunk: &Chunk) -> u64 { let mut bits = 0u64; for (i, s) in chunk.sections.iter().enumerate() { - let mut unpacked = [0u16; BLOCKS]; - s.unpack(&mut unpacked); - let any = unpacked - .iter() - .any(|&v| self.flags.get(usize::from(v)).copied().unwrap_or(0) & NON_AIR != 0); - if any { + if self.cached(s, |e| e.non_air) { bits |= 1 << i; } } @@ -234,10 +348,10 @@ impl ChunkEncoder { chunk: &Chunk, block_entities: &HashMap<(i32, i32, i32), BlockEntity>, ) -> LevelChunkWithLight { - let mut sections = Vec::with_capacity(SECTIONS); + let mut buffer = Vec::new(); let mut entity_infos = Vec::new(); for (i, s) in chunk.sections.iter().enumerate() { - let (encoded, has_entities) = self.section(s); + let (encoded, has_entities) = self.section_wire(s); if has_entities { for y in 0..16 { for z in 0..16 { @@ -261,7 +375,7 @@ impl ChunkEncoder { } } } - sections.push(encoded); + buffer.extend_from_slice(&encoded); } // A loaded chunk's block entities enter its maps in the save's order // (ChunkAccess.pendingBlockEntities, then LevelChunk.blockEntities): @@ -293,9 +407,9 @@ impl ChunkEncoder { heightmaps: self .tables .as_ref() - .map(|t| crate::save::client_heightmaps(chunk, t)) + .map(|t| self.heightmaps(chunk, t)) .unwrap_or_default(), - buffer: ChunkData::from_sections(§ions), + buffer, block_entities: entity_infos, }, light: light_data(chunk, u64::MAX), @@ -398,31 +512,26 @@ fn light_data(chunk: &Chunk, around: u64) -> LightData { _ => &chunk.sections[b - 1].light, }; let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]); - let (mut sky_any, mut block_any) = (false, false); - match light { + let (sky_any, block_any) = match light { Light::Uniform(v) => { let (sk, bl) = (v >> 4, v & 15); - sky_any = sk != 0; - block_any = bl != 0; - let (sb, bb) = (sk | sk << 4, bl | bl << 4); - sky.fill(sb); - block.fill(bb); + sky.fill(sk | sk << 4); + block.fill(bl | bl << 4); + (sk != 0, bl != 0) } Light::Full(a) => { - for (j, &v) in a.iter().enumerate() { - let (sk, bl) = (v >> 4, v & 15); - sky_any |= sk != 0; - block_any |= bl != 0; - if j & 1 == 0 { - sky[j >> 1] |= sk; - block[j >> 1] |= bl; - } else { - sky[j >> 1] |= sk << 4; - block[j >> 1] |= bl << 4; - } + // Two blocks per byte, the even one in the low nibble. + for ((pair, sky), block) in + a.as_chunks::<2>().0.iter().zip(&mut sky).zip(&mut block) + { + let [even, odd] = *pair; + *sky = even >> 4 | (odd & 0xF0); + *block = (even & 15) | odd << 4; } + let all = a.iter().fold(0u8, |acc, &v| acc | v); + (all & 0xF0 != 0, all & 15 != 0) } - } + }; if sky_any { set_bit(&mut data.sky_mask, b); data.sky.push(sky); @@ -460,6 +569,66 @@ mod tests { assert_eq!(block_entity_type("minecraft:stone"), None); } + fn encoder() -> ChunkEncoder { + let states = ["minecraft:air", "minecraft:stone", "minecraft:water"] + .map(|n| (Arc::::from(n), n.ends_with("water"))); + ChunkEncoder::new(states, &Builtin::default(), &[], &[]) + } + + /// The bytes on the wire for a section, encoded afresh. + fn fresh(encoder: &ChunkEncoder, section: &Section) -> Vec { + let mut w = horizon_protocol::buf::Writer::new(); + encoder.section(section).0.write(&mut w); + w.data + } + + #[test] + fn cached_sections_follow_edits() { + let encoder = encoder(); + let mut chunk = Chunk::empty(0, 0); + chunk.set(1, MIN_Y + 2, 3, 1); + let before = encoder.encode(&chunk, &HashMap::new()); + assert_eq!(encoder.occupied(&chunk), 1); + assert_eq!( + &*encoder.section_wire(&chunk.sections[0]).0, + fresh(&encoder, &chunk.sections[0]) + ); + // An edit moves the section: the cache sees a new one. + chunk.set(4, MIN_Y + 20, 4, 2); + chunk.set(1, MIN_Y + 2, 3, 0); + assert_eq!(encoder.occupied(&chunk), 2); + let after = encoder.encode(&chunk, &HashMap::new()); + assert_ne!(before.chunk.buffer, after.chunk.buffer); + let mut expected = Vec::new(); + for s in &chunk.sections { + expected.extend(fresh(&encoder, s)); + } + assert_eq!(after.chunk.buffer, expected); + } + + #[test] + fn light_layers_pack_two_blocks_per_byte() { + let mut chunk = Chunk::empty(0, 0); + let mut light = Box::new([0u8; 4096]); + for (i, v) in light.iter_mut().enumerate() { + *v = (i * 37 % 251) as u8; + } + Arc::make_mut(&mut chunk.sections[3]).light = Light::Full(light.clone()); + let data = light_data(&chunk, u64::MAX); + // Layer 4 holds section 3. Below the world (layer 0) there is no sky + // light, so the sky layers listed start at layer 1; section 3 has the + // only block light. + let (sky, block) = (&data.sky[3], &data.block[0]); + for j in 0..4096 { + let (s, b) = if j & 1 == 0 { + (sky[j >> 1] & 15, block[j >> 1] & 15) + } else { + (sky[j >> 1] >> 4, block[j >> 1] >> 4) + }; + assert_eq!((s, b), (light[j] >> 4, light[j] & 15), "block {j}"); + } + } + #[test] fn light_masks_cover_the_world_plus_borders() { let chunk = Chunk::empty(0, 0); diff --git a/crates/horizon-protocol/src/chunk.rs b/crates/horizon-protocol/src/chunk.rs index 3343eacf5..32d7f98b6 100644 --- a/crates/horizon-protocol/src/chunk.rs +++ b/crates/horizon-protocol/src/chunk.rs @@ -114,6 +114,67 @@ impl Paletted { /// Pack values the way the server's container would have grown: /// the smallest configuration for the number of distinct values. pub fn from_values(values: &[i32], strategy: Strategy, global_bits: u8) -> Self { + // Palette indices by value, in first-seen order: a table over the + // value range (registry ids are small), kept per thread and cleared + // after use, with the previous value remembered, since neighbouring + // blocks repeat. + thread_local! { + static INDEX: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let max = values.iter().copied().max().unwrap_or(0); + if values.iter().any(|&v| v < 0) || max >= 1 << 20 { + return Self::from_values_slow(values, strategy, global_bits); + } + let mut palette: Vec = Vec::new(); + let mut ids = Vec::with_capacity(values.len()); + INDEX.with_borrow_mut(|index| { + if index.len() <= max as usize { + index.resize(max as usize + 1, u32::MAX); + } + let (mut last, mut last_id) = (-1i32, 0u32); + for &v in values { + if v != last { + let slot = &mut index[v as usize]; + if *slot == u32::MAX { + *slot = palette.len() as u32; + palette.push(v); + } + (last, last_id) = (v, *slot); + } + ids.push(last_id); + } + for &v in &palette { + index[v as usize] = u32::MAX; + } + }); + let needed = if palette.len() <= 1 { + 0 + } else { + (usize::BITS - (palette.len() - 1).leading_zeros()) as u8 + }; + let (has_palette, bits) = strategy.configuration(needed, global_bits); + if bits == 0 { + return Self { + bits: 0, + palette: vec![palette.first().copied().unwrap_or(0)], + data: Vec::new(), + }; + } + let mut data = vec![0i64; storage_len(bits, values.len())]; + let per = 64 / bits as usize; + for (i, (&v, &id)) in values.iter().zip(&ids).enumerate() { + let id = if has_palette { u64::from(id) } else { v as u64 }; + data[i / per] |= (id << ((i % per) * bits as usize)) as i64; + } + Self { + bits, + palette: if has_palette { palette } else { Vec::new() }, + data, + } + } + + /// `from_values` for any values: linear palette searches. + fn from_values_slow(values: &[i32], strategy: Strategy, global_bits: u8) -> Self { let mut palette: Vec = Vec::new(); for &v in values { if !palette.contains(&v) { @@ -290,6 +351,29 @@ pub fn nibble(layer: &[u8], i: usize) -> u8 { mod tests { use super::*; + #[test] + fn from_values_matches_the_linear_search() { + let mut seed = 12345u64; + let mut next = |n: u64| { + seed = seed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + ((seed >> 33) % n) as i32 + }; + for distinct in [1u64, 2, 16, 17, 200, 300, 5000] { + let values: Vec = (0..BLOCKS).map(|_| next(distinct) * 7).collect(); + assert_eq!( + Paletted::from_values(&values, Strategy::Blocks, 16), + Paletted::from_values_slow(&values, Strategy::Blocks, 16) + ); + let biomes: Vec = values[..BIOMES].to_vec(); + assert_eq!( + Paletted::from_values(&biomes, Strategy::Biomes, 7), + Paletted::from_values_slow(&biomes, Strategy::Biomes, 7) + ); + } + } + #[test] fn bit_storage_matches_simple_bit_storage() { // 5 bits: 12 values per long, the top 4 bits of each long unused. From 0789bf071926d6cf9ced552f916f1d4bc712f9c7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:06:23 +0200 Subject: [PATCH 010/327] Keep the behaviours snapshot in the game folder, keyed to the build The resource folder is shared: worktrees and parity harnesses link one copy, and the launcher copies a prepared folder to each new compatible version. A snapshot there would be read by builds that resolve the tables differently while the VERSION constant stays the same. Keep it in the game's own .horizon-cache (set by the client; tools, tests and servers don't cache), add the running executable to its key, and skip hashing the resources when there is no snapshot. Postcard without default features drops heapless and the unmaintained atomic-polyfill from the lockfile. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + Cargo.lock | 54 ----------- crates/horizon-client/src/game.rs | 3 + crates/horizon-world/Cargo.toml | 2 +- crates/horizon-world/src/level/data.rs | 1 + crates/horizon-world/src/level/data/cache.rs | 94 ++++++++++++++++---- crates/horizon-world/src/level/mod.rs | 6 ++ 7 files changed, 88 insertions(+), 73 deletions(-) diff --git a/.gitignore b/.gitignore index eb29ad10d..7fffd6a99 100644 --- a/.gitignore +++ b/.gitignore @@ -28,5 +28,6 @@ /horizon-player.txt /servers.dat /screenshots/ +/.horizon-cache/ /crash-reports/ /debug/ diff --git a/Cargo.lock b/Cargo.lock index 9726316b6..ea6681a2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -196,15 +196,6 @@ dependencies = [ "libloading", ] -[[package]] -name = "atomic-polyfill" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" -dependencies = [ - "critical-section", -] - [[package]] name = "atomic-waker" version = "1.1.2" @@ -331,12 +322,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "bytes" version = "1.12.1" @@ -757,12 +742,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1328,15 +1307,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "hash32" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" -dependencies = [ - "byteorder", -] - [[package]] name = "hashbrown" version = "0.15.5" @@ -1367,20 +1337,6 @@ dependencies = [ "foldhash 0.2.0", ] -[[package]] -name = "heapless" -version = "0.7.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" -dependencies = [ - "atomic-polyfill", - "hash32", - "rustc_version", - "serde", - "spin", - "stable_deref_trait", -] - [[package]] name = "heck" version = "0.5.0" @@ -2919,7 +2875,6 @@ dependencies = [ "cobs", "embedded-io 0.4.0", "embedded-io 0.6.1", - "heapless", "serde", ] @@ -3506,15 +3461,6 @@ dependencies = [ "sha2", ] -[[package]] -name = "spin" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" -dependencies = [ - "lock_api", -] - [[package]] name = "spirv" version = "0.4.0+sdk-1.4.341.0" diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e552eb118..6dbaba66d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10144,6 +10144,9 @@ pub fn run() -> Result<()> { horizon_client::spans::enable(options.spikes.is_some()); let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); + // Snapshots of derived tables live in the game folder, never beside the + // shared resources. + Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache")); options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs); options.resources = mods::content_root( &options.resources, diff --git a/crates/horizon-world/Cargo.toml b/crates/horizon-world/Cargo.toml index 3e5f9466d..737edd289 100644 --- a/crates/horizon-world/Cargo.toml +++ b/crates/horizon-world/Cargo.toml @@ -11,7 +11,7 @@ libm = "=0.2.16" serde_json = { version = "1.0.151", features = ["raw_value"] } serde = { version = "1", features = ["derive"] } sha2 = "0.10" -postcard = { version = "=1.1.3", features = ["alloc"] } +postcard = { version = "=1.1.3", default-features = false, features = ["alloc"] } horizon-core = { path = "../horizon-core" } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } lz4_flex = { version = "0.14", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] } diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 83349232c..ef47294a8 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -23,6 +23,7 @@ use std::{ }; #[path = "data/cache.rs"] mod cache; +pub(super) use cache::set_dir as set_cache_dir; /// Per-state flags read from vanilla accessors over an empty level. pub mod state_flags { diff --git a/crates/horizon-world/src/level/data/cache.rs b/crates/horizon-world/src/level/data/cache.rs index f143cf6cd..59bc1f8d8 100644 --- a/crates/horizon-world/src/level/data/cache.rs +++ b/crates/horizon-world/src/level/data/cache.rs @@ -2,21 +2,36 @@ //! //! The source resources remain authoritative. Failed reads, unsupported //! versions, corrupt payloads and write failures always use the normal loader. +//! The snapshot lives in the game's own cache folder ([`set_dir`]), never in the +//! resource folder: that one is shared by worktrees and copied between installed +//! versions by the launcher. Its key includes the running executable, so a build +//! that resolves the tables differently never reads another build's snapshot. use super::*; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ io::Write, path::PathBuf, - sync::atomic::{AtomicU64, Ordering}, + sync::{ + OnceLock, + atomic::{AtomicU64, Ordering}, + }, + time::UNIX_EPOCH, }; const MAGIC: &[u8; 8] = b"HZBEHAV\0"; const VERSION: u32 = 2; -const FILE_NAME: &str = ".horizon-behaviours-v2.bin"; +const FILE_NAME: &str = "behaviours-v2.bin"; const MAX_FILE_BYTES: usize = 128 * 1024 * 1024; const MAX_DECODED_BYTES: usize = 256 * 1024 * 1024; static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); +static DIR: OnceLock = OnceLock::new(); + +/// Keep snapshots in `dir` (the client passes `/.horizon-cache`). +/// Without it (tests, tools, servers), `Behaviours::load` always uses the source loader. +pub(in crate::level) fn set_dir(dir: PathBuf) { + let _ = DIR.set(dir); +} #[derive(Serialize, Deserialize)] struct Snapshot { @@ -123,6 +138,17 @@ struct Item { fn fingerprint(registry: &BlockRegistry, root: &Path) -> io::Result<[u8; 32]> { let mut hasher = Sha256::new(); hasher.update(b"horizon resolved behaviours 2"); + // The build that resolved the tables: the version constant alone misses + // loader changes that keep the snapshot layout. + let exe = std::env::current_exe()?; + let built = fs::metadata(&exe)?; + hash_str(&mut hasher, &exe.to_string_lossy()); + hasher.update(built.len().to_le_bytes()); + let modified = built + .modified()? + .duration_since(UNIX_EPOCH) + .map_err(|e| invalid(e.to_string()))?; + hasher.update(modified.as_nanos().to_le_bytes()); for relative in [ "facts.json", "block-behaviours.json", @@ -635,8 +661,12 @@ impl Snapshot { } pub(super) fn load(registry: &BlockRegistry, root: &Path) -> Option { + load_from(DIR.get()?, registry, root) +} + +fn load_from(dir: &Path, registry: &BlockRegistry, root: &Path) -> Option { + let bytes = fs::read(dir.join(FILE_NAME)).ok()?; let fingerprint = fingerprint(registry, root).ok()?; - let bytes = fs::read(root.join(FILE_NAME)).ok()?; // Validate bounds before decoding untrusted cache contents. if bytes.len() < 8 + 4 + 32 + 32 || bytes.len() > MAX_FILE_BYTES { return None; @@ -661,10 +691,17 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> Option } pub(super) fn store(registry: &BlockRegistry, root: &Path, behaviours: &Behaviours) { - let _ = write(registry, root, behaviours); + if let Some(dir) = DIR.get() { + let _ = write(dir, registry, root, behaviours); + } } -fn write(registry: &BlockRegistry, root: &Path, behaviours: &Behaviours) -> io::Result<()> { +fn write( + dir: &Path, + registry: &BlockRegistry, + root: &Path, + behaviours: &Behaviours, +) -> io::Result<()> { let fingerprint = fingerprint(registry, root)?; let snapshot = Snapshot::capture(behaviours); let serialized = postcard::to_allocvec(&snapshot).map_err(|e| invalid(e.to_string()))?; @@ -678,8 +715,9 @@ fn write(registry: &BlockRegistry, root: &Path, behaviours: &Behaviours) -> io:: bytes.extend_from_slice(&fingerprint); bytes.extend_from_slice(&Sha256::digest(&body)); bytes.extend_from_slice(&body); - let path = root.join(FILE_NAME); - let tmp = root.join(format!( + fs::create_dir_all(dir)?; + let path = dir.join(FILE_NAME); + let tmp = dir.join(format!( "{FILE_NAME}.tmp-{}-{}", std::process::id(), NEXT_TEMP.fetch_add(1, Ordering::Relaxed) @@ -773,11 +811,25 @@ mod tests { let Some(root) = fixture() else { return; }; + // The game's cache folder, apart from the resources. + let dir = root.0.join("game/.horizon-cache"); let registry = super::super::load_registry(&root.0).unwrap(); - assert!(load(®istry, &root.0).is_none()); - let initial = super::super::load(®istry, &root.0).unwrap(); - assert!(root.0.join(FILE_NAME).is_file()); - let hit = load(®istry, &root.0).expect("cache hit"); + // What `data::load` does once `set_dir` gave it a folder. + let load_or_build = || { + load_from(&dir, ®istry, &root.0).unwrap_or_else(|| { + let built = super::super::load_uncached(®istry, &root.0).unwrap(); + write(&dir, ®istry, &root.0, &built).unwrap(); + built + }) + }; + assert!(load_from(&dir, ®istry, &root.0).is_none()); + let initial = load_or_build(); + assert!(dir.join(FILE_NAME).is_file()); + assert!( + !root.0.join(FILE_NAME).exists(), + "the resource folder stays untouched" + ); + let hit = load_from(&dir, ®istry, &root.0).expect("cache hit"); assert_eq!(initial.table.state_count(), hit.table.state_count()); let tags = root.0.join("block-tags.json"); fs::OpenOptions::new() @@ -787,23 +839,29 @@ mod tests { .write_all(b"\n") .unwrap(); assert!( - load(®istry, &root.0).is_none(), + load_from(&dir, ®istry, &root.0).is_none(), "changed resource must invalidate" ); - super::super::load(®istry, &root.0).expect("source fallback"); + load_or_build(); assert!( - load(®istry, &root.0).is_some(), + load_from(&dir, ®istry, &root.0).is_some(), "fallback should replace cache" ); - let cache_file = root.0.join(FILE_NAME); + let cache_file = dir.join(FILE_NAME); let mut bytes = fs::read(&cache_file).unwrap(); bytes[80] ^= 0x80; fs::write(&cache_file, bytes).unwrap(); assert!( - load(®istry, &root.0).is_none(), + load_from(&dir, ®istry, &root.0).is_none(), "checksum failure must invalidate" ); - super::super::load(®istry, &root.0).expect("corrupt cache fallback"); - assert!(load(®istry, &root.0).is_some()); + load_or_build(); + assert!(load_from(&dir, ®istry, &root.0).is_some()); + // A snapshot written under another key (another build of the game, + // other resources) is never trusted. + let mut other = fs::read(&cache_file).unwrap(); + other[12] ^= 1; + fs::write(&cache_file, other).unwrap(); + assert!(load_from(&dir, ®istry, &root.0).is_none()); } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 00dd115db..cc561993a 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -456,6 +456,12 @@ impl Behaviours { pub fn load(registry: &BlockRegistry, resources_dir: &Path) -> io::Result { data::load(registry, resources_dir) } + /// Keep a snapshot of the resolved tables in `dir` (a game folder's + /// `.horizon-cache`), so later launches of the same build restore it instead + /// of resolving the resources again. Without it, [`Self::load`] never caches. + pub fn set_cache_dir(dir: std::path::PathBuf) { + data::set_cache_dir(dir); + } pub fn facts(&self, state: BlockStateId) -> &StateFacts { &self.facts[state.0 as usize] } From 2e98f6a18a8977f5a5c567f731370dbb4b2d197c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:25:02 +0200 Subject: [PATCH 011/327] Let the behaviour profiler use a snapshot folder Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/examples/behaviour_load_profile.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-world/examples/behaviour_load_profile.rs b/crates/horizon-world/examples/behaviour_load_profile.rs index e6619afa1..d9d7a1147 100644 --- a/crates/horizon-world/examples/behaviour_load_profile.rs +++ b/crates/horizon-world/examples/behaviour_load_profile.rs @@ -1,4 +1,6 @@ //! Measure registry and behaviour load times using prepared client resources. +//! `behaviour_load_profile RESOURCES [CACHE_DIR]`: with CACHE_DIR, loads use and +//! refresh the snapshot there, as the client does with its `.horizon-cache`. use horizon_world::level::{Behaviours, data::load_registry}; use std::{path::Path, time::Instant}; @@ -7,6 +9,9 @@ fn main() -> Result<(), Box> { .nth(1) .expect("resource directory argument"); let root = Path::new(&root); + if let Some(dir) = std::env::args().nth(2) { + Behaviours::set_cache_dir(dir.into()); + } let started = Instant::now(); let registry = load_registry(root)?; eprintln!( From 02dce1093be2cbb0dcfc3f8bfd3267030facf176 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:58:28 +0200 Subject: [PATCH 012/327] Give the behaviour profiler its own name Every PR of the startup batch adds a different tools/profile_client_startup.py, so any two of them conflict. This one measures only Behaviours::load, so it becomes tools/profile_behaviour_cache.py, and --cache-dir passes the snapshot folder to the example so warm loads can be measured. Co-Authored-By: Claude Opus 5.5 --- ...lient_startup.py => profile_behaviour_cache.py} | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) rename tools/{profile_client_startup.py => profile_behaviour_cache.py} (74%) diff --git a/tools/profile_client_startup.py b/tools/profile_behaviour_cache.py similarity index 74% rename from tools/profile_client_startup.py rename to tools/profile_behaviour_cache.py index 76ad9002c..00ba65a6d 100644 --- a/tools/profile_client_startup.py +++ b/tools/profile_behaviour_cache.py @@ -5,7 +5,10 @@ Build the behaviour_load_profile example in the checkout to be measured first: cargo build --release -p horizon-world --example behaviour_load_profile Run the profiler from the repository root with the matching example binary. -This measures behaviour loading, not time to first rendered frame. +This measures behaviour loading, not time to first rendered frame. With +--cache-dir, the example reads and refreshes the resolved snapshot there, as the +client does with its .horizon-cache folder: the first load of a run builds it +when it is missing, the next loads restore it. """ import argparse import json @@ -19,6 +22,8 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", type=Path, default=Path("target/release/examples/behaviour_load_profile")) parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3")) + parser.add_argument("--cache-dir", type=Path, + help="snapshot folder (default: no snapshot, every load is uncached)") parser.add_argument("--repeats", type=int, default=5) parser.add_argument("--output", type=Path) args = parser.parse_args() @@ -26,8 +31,10 @@ def main(): parser.error("--repeats must be at least one") samples = [] for _ in range(args.repeats): - run = subprocess.run([str(args.binary.resolve()), str(args.resources.resolve())], - text=True, capture_output=True, check=True) + command = [str(args.binary.resolve()), str(args.resources.resolve())] + if args.cache_dir: + command.append(str(args.cache_dir.resolve())) + run = subprocess.run(command, text=True, capture_output=True, check=True) values = {key: float(value) for key, value in re.findall(r"^(registry_ms|behaviours_[0-2]_ms)=([\d.]+)$", run.stderr, re.M)} if len(values) != 4: @@ -38,6 +45,7 @@ def main(): for key in samples[0]} result = {"scope": "behaviour loader only; not full client startup", "binary": str(args.binary), "resources": str(args.resources), "repeats": args.repeats, + "cache_dir": str(args.cache_dir) if args.cache_dir else None, "metrics": summary} print(json.dumps(result, indent=2)) if args.output: From b347ceb19511017831a268667c2a320794502333 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:45:46 +0200 Subject: [PATCH 013/327] Dedicated server: vanilla's chunk pacing and movement checks PlayerChunkSender: one unacknowledged batch until the client's first acknowledgement and ten after it, batches capped at the client's desired chunks per tick (not twice that), and the quota reset to one chunk whenever every batch is acknowledged. ServerGamePacketListenerImpl.handleMovePlayer: a move further from where the tick began (firstGood) than 100 blocks squared per move packet (300 while gliding; the count falls back to 1 past 5 packets) logs " moved too quickly!" and pulls the player back, as the player_movement_check and elytra_movement_check game rules allow. NaN coordinates or non-finite angles and two position moves in one client tick disconnect with invalid_player_movement, positions are clamped to the world's limits, an unanswered teleport is sent again after 20 ticks, and accepting a teleport runs the move it carries. The move is then replayed against the blocks: a survival or adventure player who ends more than 0.25 blocks short of the target (horizontally; vanilla drops the vertical part) logs " moved wrongly!" and is sent back unless they were already stuck, and any move into a block the old box did not touch (isEntityCollidingWithAnythingNew) is sent back silently. Spectators and sleepers skip both. Angles wrap as Mth.wrapDegrees does. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/lan_flat.rs | 3 +- crates/horizon-client/src/game/lan.rs | 10 + crates/horizon-client/src/lan/guest.rs | 26 +- crates/horizon-client/src/lan/hub.rs | 299 ++++++++++++++++++--- crates/horizon-client/tests/lan_bot.rs | 1 + 5 files changed, 297 insertions(+), 42 deletions(-) diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 16fc36b95..d1a492edf 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -121,6 +121,7 @@ fn main() -> Result<(), Box> { clock_rate: 1.0, tick_rate: 20.0, tick_frozen: false, + collision: None, }; for event in hub.tick(&mut ctx) { match event { @@ -132,7 +133,7 @@ fn main() -> Result<(), Box> { eprintln!("[lan] {packet:?}"); } } - HostEvent::Chat(line) => println!("{line}"), + HostEvent::Chat(line) | HostEvent::Warn(line) => println!("{line}"), HostEvent::Left(_) => {} } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 1d00134e4..ad30dd813 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -710,7 +710,12 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; + host.hub.movement_checks = ( + self.ui.rules.bool("player_movement_check"), + self.ui.rules.bool("elytra_movement_check"), + ); host.hub.tick(&mut ctx) }; if let Some(state) = &state @@ -772,6 +777,10 @@ impl Game<'_> { super::dedicated::log("INFO", &format!("[Not Secure] {line}")); } HostEvent::Chat(line) => self.system_message(Text::literal(line)), + HostEvent::Warn(line) if self.options.dedicated.is_some() => { + super::dedicated::log("WARN", &line); + } + HostEvent::Warn(line) => log::warn!("{line}"), HostEvent::Packet(conn, packet) => { self.lan_guest_packet(&mut host, conn, *packet); } @@ -831,6 +840,7 @@ impl Game<'_> { clock_rate: self.ui.clock.rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; host.hub.place_new_player(conn, &mut ctx); } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 243c90d18..28b833d3c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -71,15 +71,31 @@ pub struct Guest { /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, pub teleport_counter: i32, + /// The hub tick the pending teleport was (re)sent on (awaitingTeleportTime). + pub teleport_tick: u64, + /// Where the player was when this tick's packets began (firstGoodX/Y/Z), + /// for the moved-too-quickly check. + pub first_good: [f64; 3], + /// Position moves received in all and by the start of this tick + /// (receivedMovePacketCount, knownMovePacketCount). + pub received_moves: i32, + pub known_moves: i32, + /// A position move arrived since the client's last ClientTickEnd + /// (receivedPositionThisTick): a second one is a protocol error. + pub position_this_tick: bool, /// The client finished loading terrain (ServerboundPlayerLoadedPacket). pub loaded: bool, // Chunks. pub center: Option<(i32, i32)>, pub sent_chunks: HashSet<(i32, i32)>, pub chunk_queue: Vec<(i32, i32)>, + /// PlayerChunkSender: batches sent but not yet acknowledged, how many + /// may be (1 until the client's first acknowledgement, then 10), the + /// rate the client asks for and the chunks the next batch may hold. pub unacknowledged: u32, + pub max_unacknowledged: u32, pub chunks_per_tick: f32, - pub chunk_credit: f32, + pub batch_quota: f32, // Entities. pub tracker: Tracker, // Player state the gameplay code reads and writes. @@ -167,13 +183,19 @@ impl Guest { sleeping: false, awaiting_teleport: None, teleport_counter: 0, + teleport_tick: 0, + first_good: position, + received_moves: 0, + known_moves: 0, + position_this_tick: false, loaded: false, center: None, sent_chunks: HashSet::new(), chunk_queue: Vec::new(), unacknowledged: 0, + max_unacknowledged: 1, chunks_per_tick: 9.0, - chunk_credit: 0.0, + batch_quota: 0.0, tracker: Tracker::default(), motion: None, inventory: vec![None; 36], diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index cb438508e..b0e30c664 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,17 +12,24 @@ use super::{ guest::{Guest, SentEffect, stack_to_network}, }; use crate::{ + collisions::SceneCollisions, effects::{EffectInstance, PlayerEffects}, items::ItemStack, world::World, }; +use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ entity_data::{Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; -use horizon_world::nbt::{JavaString, Tag}; +use horizon_world::{ + block_collision::BlockCollisionRegistry, + block_collision_scan::BlockCollisionScan, + collision_context::CollisionContext, + nbt::{JavaString, Tag}, +}; use std::sync::{Arc, atomic::Ordering}; /// GameEvent types (ClientboundGameEventPacket). @@ -88,6 +95,9 @@ pub struct TickCtx<'a> { /// TickRateManager: the tick rate and whether the game is frozen. pub tick_rate: f32, pub tick_frozen: bool, + /// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly + /// check (none: moves are not checked against blocks). + pub collision: Option<&'a BlockCollisionRegistry<'a>>, } /// What the gameplay code has to do for a guest. @@ -99,6 +109,8 @@ pub enum HostEvent { Packet(u32, Box), /// A chat line to show on the host (already broadcast to the guests). Chat(String), + /// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn). + Warn(String), } pub struct Hub { @@ -108,6 +120,9 @@ pub struct Hub { pub guests: Vec, pub(super) sync: Arc, pub ticks: u64, + /// The `player_movement_check` and `elytra_movement_check` game rules, + /// set by the game before each tick. + pub movement_checks: (bool, bool), last_clock: i64, last_rate: f32, ticking: (f32, bool), @@ -196,6 +211,7 @@ impl Hub { guests: Vec::new(), sync, ticks: 0, + movement_checks: (true, true), last_clock: i64::MIN, last_rate: 0.0, ticking: (20.0, false), @@ -713,7 +729,9 @@ impl Hub { /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { + let ticks = self.ticks; let g = &mut self.guests[i]; + g.teleport_tick = ticks; if let Some(p) = position { g.position = p; g.previous_position = p; @@ -1051,15 +1069,16 @@ impl Hub { g.chunk_queue .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); } - // Send ready chunks, closest first, in batches. - if g.chunk_queue.is_empty() || g.unacknowledged >= 10 || self.ticks <= g.placed_at + 1 { + // PlayerChunkSender.sendNextChunks: ready chunks, closest first, in + // batches the client's acknowledgements pace. + if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged { return; } - g.chunk_credit = (g.chunk_credit + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0) * 2.0); - let budget = g.chunk_credit.floor() as usize; - if budget == 0 { + g.batch_quota = (g.batch_quota + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0)); + if g.batch_quota < 1.0 || g.chunk_queue.is_empty() { return; } + let budget = g.batch_quota.floor() as usize; let mut packets = Vec::new(); let mut taken = Vec::new(); for (idx, key) in g.chunk_queue.iter().enumerate() { @@ -1080,7 +1099,7 @@ impl Hub { if packets.is_empty() { return; } - g.chunk_credit -= packets.len() as f32; + g.batch_quota -= packets.len() as f32; g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); for p in &packets { g.send(p); @@ -1462,6 +1481,11 @@ impl Hub { } fn process_inbox(&mut self, i: usize, ctx: &mut TickCtx, events: &mut Vec) { + // ServerGamePacketListenerImpl.tickPlayer ran between the last + // tick's packets and these: resetPosition, and the moves it counted. + let g = &mut self.guests[i]; + g.first_good = g.position; + g.known_moves = g.received_moves; let mut budget = 400; while budget > 0 { let Some(packet) = self.guests[i].inbox.pop_front() else { @@ -1490,23 +1514,42 @@ impl Hub { self.guests[i].last_action_tick = self.ticks; } match packet { + // handleAcceptTeleportPacket. S::AcceptTeleportation(p) => { let g = &mut self.guests[i]; - if g.awaiting_teleport.is_some_and(|(id, _)| id == p.id) { + if let Some((id, at)) = g.awaiting_teleport + && id == p.id + { + if p.x.is_nan() + || p.y.is_nan() + || p.z.is_nan() + || !p.yaw.is_finite() + || !p.pitch.is_finite() + { + self.kick(conn, invalid_movement()); + continue; + } + g.position = at; g.awaiting_teleport = None; + let rot = (p.yaw, p.pitch); + self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events); } } S::MovePlayerPos(p) => { - self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags); + self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events); } S::MovePlayerPosRot(p) => { - self.move_player(i, Some([p.x, p.y, p.z]), Some((p.yaw, p.pitch)), p.flags); + let (pos, rot) = ([p.x, p.y, p.z], (p.yaw, p.pitch)); + self.move_player(i, Some(pos), Some(rot), p.flags, ctx, events); } S::MovePlayerRot(p) => { - self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags); + self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags, ctx, events); + } + S::MovePlayerStatus(p) => { + self.move_player(i, None, None, p.flags, ctx, events); } - S::MovePlayerStatus(p) => self.move_player(i, None, None, p.flags), S::PlayerLoaded(_) => self.guests[i].loaded = true, + // PlayerChunkSender.onChunkBatchReceivedByClient. S::ChunkBatchReceived(p) => { let g = &mut self.guests[i]; g.unacknowledged = g.unacknowledged.saturating_sub(1); @@ -1515,7 +1558,12 @@ impl Hub { } else { p.chunks_per_tick.clamp(0.01, 64.0) }; + if g.unacknowledged == 0 { + g.batch_quota = 1.0; + } + g.max_unacknowledged = 10; } + S::ClientTickEnd(_) => self.guests[i].position_this_tick = false, S::ClientInformation(info) => { let g = &mut self.guests[i]; g.view_distance = @@ -1534,7 +1582,6 @@ impl Hub { 0 => self.guests[i].sleeping = false, _ => {} }, - S::ClientTickEnd(_) => {} S::Chat(c) => { let text: String = c.message.chars().filter(|c| !c.is_control()).collect(); if !text.is_empty() { @@ -1546,48 +1593,205 @@ impl Hub { other => events.push(HostEvent::Packet(conn, Box::new(other))), } } - let _ = ctx; } /// ServerGamePacketListenerImpl.handleMovePlayer. - fn move_player(&mut self, i: usize, pos: Option<[f64; 3]>, rot: Option<(f32, f32)>, flags: u8) { - let g = &mut self.guests[i]; - if g.awaiting_teleport.is_some() || !g.loaded && g.ticks == 0 && pos.is_none() { + fn move_player( + &mut self, + i: usize, + pos: Option<[f64; 3]>, + rot: Option<(f32, f32)>, + flags: u8, + ctx: &TickCtx, + events: &mut Vec, + ) { + let conn = self.guests[i].conn; + // containsInvalidValues, on the packet's values (0 where it has none). + let (yaw, pitch) = rot.unwrap_or_default(); + if pos.is_some_and(|p| p.iter().any(|v| v.is_nan())) + || !yaw.is_finite() + || !pitch.is_finite() + { + self.kick(conn, invalid_movement()); return; } - if let Some(p) = pos { - if p.iter().any(|v| !v.is_finite() || v.abs() > 3.0e7) { + let g = &mut self.guests[i]; + if pos.is_some() { + if g.position_this_tick { + self.kick(conn, invalid_movement()); return; } - // A jump of more than a hundred blocks is a rejected move. - let d2: f64 = (0..3).map(|k| (p[k] - g.position[k]).powi(2)).sum(); - if d2 > 100.0 * 100.0 { - let at = g.position; - self.teleport(i, Some(at)); - return; - } - g.previous_position = g.position; - g.position = p; + g.position_this_tick = true; } - let moved = pos.map_or([0.0; 3], |_| { - [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]) - }); + if !g.loaded && g.ticks == 0 && pos.is_none() { + return; + } + // updateAwaitingTeleport: moves wait for the client to accept the + // teleport, which is sent again after 20 ticks without an answer. + if let Some((_, at)) = g.awaiting_teleport { + if self.ticks - g.teleport_tick > 20 { + self.teleport(i, Some(at)); + } + return; + } + let to = pos.unwrap_or(g.position); + let rot = rot.unwrap_or((g.yaw, g.pitch)); + self.position_change(i, to, rot, flags, ctx, events); + } + + /// ServerGamePacketListenerImpl.handlePlayerPositionChange. + fn position_change( + &mut self, + i: usize, + to: [f64; 3], + (yaw, pitch): (f32, f32), + flags: u8, + ctx: &TickCtx, + events: &mut Vec, + ) { + let (frozen, (check, elytra_check)) = (self.ticking.1, self.movement_checks); + let g = &mut self.guests[i]; + let to = [ + to[0].clamp(-3.0E7, 3.0E7), + to[1].clamp(-2.0E7, 2.0E7), + to[2].clamp(-3.0E7, 3.0E7), + ]; + let (yaw, pitch) = (wrap_degrees(yaw), wrap_degrees(pitch)); + let d = [0, 1, 2].map(|k| to[k] - g.first_good[k]); + let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if g.sleeping { + if moved > 1.0 { + (g.yaw, g.pitch) = (yaw, pitch); + self.teleport(i, None); + } + return; + } + // TickRateManager.runsNormally: not frozen (a frozen game's steps + // are not counted either; Horizon's hub does not see them). + if !frozen { + g.received_moves += 1; + let mut packets = g.received_moves - g.known_moves; + if packets > 5 { + packets = 1; + } + // shouldCheckPlayerMovement. The server holds no velocity for a + // guest (getDeltaMovement), so nothing is expected. + if check && (!g.fall_flying || elytra_check) { + let limit = if g.fall_flying { 300.0 } else { 100.0 }; + if moved > limit * f64::from(packets) { + events.push(HostEvent::Warn(format!( + "{} moved too quickly! {},{},{}", + g.name, + crate::java_text::double_to_string(d[0]), + crate::java_text::double_to_string(d[1]), + crate::java_text::double_to_string(d[2]) + ))); + self.teleport(i, None); + return; + } + } + } + let start = g.position; + let (wrongly, refused) = self.collide(i, to, ctx); + if wrongly { + let line = format!("{} moved wrongly!", self.guests[i].name); + events.push(HostEvent::Warn(line)); + } + if refused { + let g = &mut self.guests[i]; + (g.yaw, g.pitch) = (yaw, pitch); + self.teleport(i, Some(start)); + return; + } + let g = &mut self.guests[i]; + g.previous_position = g.position; + g.position = to; + let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); if g.moves.is_empty() { g.moves_from_ground = g.on_ground; } g.moves.push((moved, flags & 1 != 0)); - if let Some((yaw, pitch)) = rot - && yaw.is_finite() - && pitch.is_finite() - { - g.yaw = yaw % 360.0; - g.pitch = pitch.clamp(-90.0, 90.0); - g.head_yaw = g.yaw; - } + g.yaw = yaw; + g.pitch = pitch.clamp(-90.0, 90.0); + g.head_yaw = g.yaw; g.on_ground = flags & 1 != 0; g.ticks = g.ticks.max(1); } + /// The collision part of handlePlayerPositionChange: whether the move + /// counts as moved wrongly (logged), and whether it is refused (the + /// player is sent back where they were). + fn collide(&self, i: usize, to: [f64; 3], ctx: &TickCtx) -> (bool, bool) { + let g = &self.guests[i]; + // noPhysics (spectators) and sleepers move freely. + let Some(binding) = ctx.collision else { + return (false, false); + }; + if g.spectator() || g.sleeping { + return (false, false); + } + let height = if g.fall_flying { + 0.6 + } else if g.sneaking { + 1.5 + } else { + 1.8 + }; + let at = |p: [f64; 3]| { + Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3), + ) + }; + let (old, new) = (at(g.position), at(to)); + let mut scene = SceneCollisions { + world: ctx.world, + binding, + subject: None, + }; + // player.move, then how far from the target it ended (vanilla drops + // the vertical part: `yDist > -0.5 || yDist < 0.5` always holds). + let movement = Vec3::new( + to[0] - g.position[0], + to[1] - g.position[1], + to[2] - g.position[2], + ); + let fail = !g.creative() + && scene + .resolve(old, movement, 0.6, g.on_ground) + .is_ok_and(|done| { + let (dx, dz) = (movement.x - done.x, movement.z - done.z); + dx * dx + dz * dz > 0.0625 + }); + if fail && scene.unobstructed(old).unwrap_or(true) { + return (true, true); + } + // isEntityCollidingWithAnythingNew: a block the old box did not + // already touch. + let shrink = f64::from(1.0E-5_f32); + let shrink = Vec3::new(shrink, shrink, shrink); + let Ok(old_shape) = VoxelShape::from_box(old.deflate(shrink)) else { + return (fail, false); + }; + let context = CollisionContext::position(g.position[1]); + let Ok(scan) = + BlockCollisionScan::new(&mut scene, context, new.deflate(shrink), false, 1 << 20) + else { + return (fail, false); + }; + for hit in scan { + let Ok(hit) = hit else { break }; + if !hit + .shape + .join_is_not_empty(&old_shape, ShapeOp::AND) + .unwrap_or(true) + { + return (fail, true); + } + } + (fail, false) + } + /// Acknowledge a block interaction (ClientboundBlockChangedAckPacket). pub fn ack(&self, conn: u32, sequence: i32) { if sequence >= 0 @@ -1684,6 +1888,23 @@ impl Hub { } /// A packet Horizon sends as raw bytes (no fields worth a type). +/// multiplayer.disconnect.invalid_player_movement. +/// Mth.wrapDegrees. +fn wrap_degrees(degrees: f32) -> f32 { + let mut wrapped = degrees % 360.0; + if wrapped >= 180.0 { + wrapped -= 360.0; + } + if wrapped < -180.0 { + wrapped += 360.0; + } + wrapped +} + +fn invalid_movement() -> Tag { + translatable("multiplayer.disconnect.invalid_player_movement", &[]) +} + fn raw(id: i32, payload: Vec) -> C { C::Unknown(id, payload) } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 36f53444c..6b1d6bd5b 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -193,6 +193,7 @@ impl Server { clock_rate: 1.0, tick_rate: 20.0, tick_frozen: false, + collision: None, }; let events = self.hub.tick(&mut ctx); for event in events { From c8003301bcab7ada444666edb09949fe9975eb99 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:45:46 +0200 Subject: [PATCH 014/327] horizon-bots: vanilla's chunk batch sizing, chunk-gated movement and chunk accounting The bots acknowledge chunk batches with ChunkBatchSizeCalculator's desired chunks per tick, from how long each batch takes to arrive, instead of a fixed 25. A bot moves only while it holds the chunk it stands in, as vanilla's client stops ticking its player in a chunk it hasn't received, so no bot outruns a server's chunk sending. Each bot keeps the chunks it holds, so the report separates chunks that entered its view from chunks sent again while it still held them, and counts the moves the server refused and the ticks it waited for its chunk. server_bench.py runs one pass per behaviour (walk, explore), spawns every bot on the world spawn itself (respawn_radius 0) so both servers see the same paths, can run the bots on another machine (--bots-via, --bots-bin, --connect) and the servers under nice, and reports new, dropped and re-sent chunks per second, pull-backs and the server's "moved too quickly" lines. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-bots/src/main.rs | 117 +++++++++++++++++++++++++++++--- tools/server_bench.py | 104 +++++++++++++++++++++------- 2 files changed, 188 insertions(+), 33 deletions(-) diff --git a/crates/horizon-bots/src/main.rs b/crates/horizon-bots/src/main.rs index d76da5e84..3eb15beec 100644 --- a/crates/horizon-bots/src/main.rs +++ b/crates/horizon-bots/src/main.rs @@ -9,6 +9,11 @@ //! horizon-bots --server 127.0.0.1:25565 --bots 25 --behaviour mixed --seconds 360 --report bots.json //! //! It prints one JSON line a second (bots online, chunks received) and writes a summary with `--report`. +//! A bot moves only while it holds the chunk it stands in: vanilla's client stops ticking its player in a chunk +//! it hasn't received, so a player can't outrun the server's chunk sending, on any server. +//! Each bot also keeps the chunks it holds, as a client's chunk cache does, so the report tells chunks that +//! entered the view apart from chunks sent again while the bot still held them (`resent`), and counts the +//! times the server pulled a bot back (`pulled_back`: a teleport after the first, as for "moved too quickly"). use horizon_protocol::{ PROTOCOL_VERSION, @@ -25,6 +30,7 @@ use horizon_protocol::{ }; use serde_json::json; use std::{ + collections::HashSet, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}, @@ -44,7 +50,7 @@ horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline m --view-distance N what the bots ask for; default 10 --seed N default 12345 --name PREFIX bot names: PREFIX0, PREFIX1...; default Bot - --report FILE a JSON summary at the end + --report FILE a JSON summary at the end (- prints it after the per-second lines) "; #[derive(Clone, Copy, Debug, PartialEq)] @@ -129,6 +135,17 @@ fn options() -> Result { struct Bot { online: AtomicBool, chunks: AtomicU64, + /// Chunks received while the bot already held them (no ForgetLevelChunk in between). + resent: AtomicU64, + /// Different chunks received over the run. + unique: AtomicU64, + forgotten: AtomicU64, + /// Teleports after the spawn one: the server refused a move. + pulled_back: AtomicU64, + /// Ticks the bot couldn't move because it didn't hold its chunk yet. + waited: AtomicU64, + /// The chunks the bot holds (ClientChunkCache). + held: Mutex>, /// Where the server last put the bot (a teleport), to start from. teleport: Mutex>, error: Mutex>, @@ -268,6 +285,36 @@ fn join(o: &Options, name: &str) -> Result { } } +/// ChunkBatchSizeCalculator: the chunks per tick a vanilla client asks for, from how long its batches take +/// to arrive. +struct BatchSize { + nanos_per_chunk: f64, + old_samples_weight: u32, + started: Instant, +} + +impl BatchSize { + fn new() -> Self { + Self { + nanos_per_chunk: 2_000_000.0, + old_samples_weight: 1, + started: Instant::now(), + } + } + fn finished(&mut self, size: i32) { + if size > 0 { + let per_chunk = self.started.elapsed().as_nanos() as f64 / f64::from(size); + let clamped = per_chunk.clamp(self.nanos_per_chunk / 3.0, self.nanos_per_chunk * 3.0); + let weight = f64::from(self.old_samples_weight); + self.nanos_per_chunk = (self.nanos_per_chunk * weight + clamped) / (weight + 1.0); + self.old_samples_weight = (self.old_samples_weight + 1).min(49); + } + } + fn desired_chunks_per_tick(&self) -> f32 { + (7_000_000.0 / self.nanos_per_chunk) as f32 + } +} + /// Reads the play state: answers what a client must answer, counts chunks, records teleports. fn read( mut reader: horizon_protocol::connection::ConnReader, @@ -277,6 +324,9 @@ fn read( use ids::play::clientbound as cb; use ids::play::serverbound as sb; let send = |body: Vec| writer.lock().unwrap().send(&body); + let mut seen = HashSet::new(); + let mut batch = BatchSize::new(); + let mut teleports = 0u64; loop { let (id, body) = match reader.recv() { Ok(packet) => packet, @@ -299,14 +349,38 @@ fn read( }, cb::LEVEL_CHUNK_WITH_LIGHT => { bot.chunks.fetch_add(1, Ordering::Relaxed); + if let (Ok(x), Ok(z)) = (r.i32(), r.i32()) { + if !bot.held.lock().unwrap().insert((x, z)) { + bot.resent.fetch_add(1, Ordering::Relaxed); + } + if seen.insert((x, z)) { + bot.unique.fetch_add(1, Ordering::Relaxed); + } + } Ok(()) } - cb::CHUNK_BATCH_FINISHED => send( - play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { - chunks_per_tick: 25.0, - }) - .encode(), - ), + cb::FORGET_LEVEL_CHUNK => { + if let Ok(play::Clientbound::ForgetLevelChunk(p)) = + play::Clientbound::decode(id, &body) + && bot.held.lock().unwrap().remove(&(p.pos[0], p.pos[1])) + { + bot.forgotten.fetch_add(1, Ordering::Relaxed); + } + Ok(()) + } + cb::CHUNK_BATCH_START => { + batch.started = Instant::now(); + Ok(()) + } + cb::CHUNK_BATCH_FINISHED => { + batch.finished(r.varint().unwrap_or(0)); + send( + play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: batch.desired_chunks_per_tick(), + }) + .encode(), + ) + } cb::PLAYER_POSITION => match play::Clientbound::decode(id, &body) { Ok(play::Clientbound::PlayerPosition(p)) => { let mut at = bot.teleport.lock().unwrap(); @@ -320,6 +394,10 @@ fn read( } }); *at = Some(pos); + teleports += 1; + if teleports > 1 { + bot.pulled_back.fetch_add(1, Ordering::Relaxed); + } send( play::Serverbound::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, @@ -416,7 +494,10 @@ fn run_bot( if let Some(at) = bot.teleport.lock().unwrap().take() { pos = at; } - if pos[1] < cruise { + let here = ((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4); + if !bot.held.lock().unwrap().contains(&here) { + bot.waited.fetch_add(1, Ordering::Relaxed); + } else if pos[1] < cruise { pos[1] = (pos[1] + 0.5).min(cruise); } else { match behaviour { @@ -520,6 +601,9 @@ fn main() { .filter(|b| b.online.load(Ordering::SeqCst)) .count(); let chunks: u64 = bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum(); + let total = |f: fn(&Bot) -> &AtomicU64| -> u64 { + bots.iter().map(|b| f(b).load(Ordering::Relaxed)).sum() + }; let failed = bots .iter() .filter(|b| b.error.lock().unwrap().is_some()) @@ -536,6 +620,11 @@ fn main() { "failed": failed, "chunks": chunks, "chunks_per_second": chunks - previous_chunks, + "unique": total(|b| &b.unique), + "forgotten": total(|b| &b.forgotten), + "resent": total(|b| &b.resent), + "pulled_back": total(|b| &b.pulled_back), + "waited_ticks": total(|b| &b.waited), }) ); previous_chunks = chunks; @@ -558,15 +647,25 @@ fn main() { "seconds": o.seconds, "joined": bots.iter().filter(|b| b.joined_after_ms.load(Ordering::SeqCst) > 0).count(), "chunks": bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum::(), + "resent": bots.iter().map(|b| b.resent.load(Ordering::Relaxed)).sum::(), + "pulled_back": bots.iter().map(|b| b.pulled_back.load(Ordering::Relaxed)).sum::(), + "waited_ticks": bots.iter().map(|b| b.waited.load(Ordering::Relaxed)).sum::(), "per_bot": bots.iter().enumerate().map(|(i, b)| json!({ "name": format!("{}{i}", o.name), "behaviour": behaviour_of(&o.behaviour, i).name(), "joined_after_ms": b.joined_after_ms.load(Ordering::SeqCst), "chunks": b.chunks.load(Ordering::Relaxed), + "unique_chunks": b.unique.load(Ordering::Relaxed), + "resent": b.resent.load(Ordering::Relaxed), + "forgotten": b.forgotten.load(Ordering::Relaxed), + "pulled_back": b.pulled_back.load(Ordering::Relaxed), + "waited_ticks": b.waited.load(Ordering::Relaxed), "error": *b.error.lock().unwrap(), })).collect::>(), }); - if let Some(path) = &o.report { + if o.report.as_deref() == Some("-") { + println!("{summary:#}"); + } else if let Some(path) = &o.report { if let Err(e) = std::fs::write(path, format!("{summary:#}\n")) { eprintln!("horizon-bots: {path}: {e}"); } diff --git a/tools/server_bench.py b/tools/server_bench.py index 5a64c80cf..91f11a7ad 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -8,10 +8,16 @@ then measures for a while: - MSPT (average, P50, P95, P99) from each server's own `/tick query`, asked every 5 seconds on the console: vanilla's ServerTickRateManager numbers, which Horizon reproduces, so both measure themselves the same way; - RSS and CPU of the server's whole process tree, once a second; -- chunks the bots receive per second (new terrain while the `explore` bots fly outwards); +- chunks the bots receive per second (new terrain while the `explore` bots fly outwards), chunks sent again + while a bot still held them, and the moves the server refused (pull-backs; "moved too quickly" and + "moved wrongly" lines); - the start time to `Done`, and every bot that failed to join or was dropped. - python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --seconds 120 + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --behaviour walk,explore + +The bots can run on another machine, so they don't take the server's CPU: `--bots-via 'ssh macmini'` with +`--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19` +runs every server at the lowest priority (a shared machine). The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The Horizon side runs target/release/horizon-server with the engine beside it; build both first: @@ -186,8 +192,16 @@ def server_command(kind, directory, args): return [server, '--dir', directory, 'run'] -def run_once(kind, bots, args, out): - directory = out / f'{kind}-{bots}' +def bots_command(args): + """horizon-bots here, or through `--bots-via` (for example `ssh macmini`) on another machine.""" + if args.bots_via: + return [*args.bots_via.split(), args.bots_bin or 'horizon-bots'] + return [args.bots_bin or BIN / f'horizon-bots{EXE}'] + + +def run_once(kind, bots, behaviour, args, out): + name = f'{kind}-{behaviour}-{bots}' + directory = out / name shutil.rmtree(directory, ignore_errors=True) directory.mkdir(parents=True) port = free_port() @@ -195,19 +209,24 @@ def run_once(kind, bots, args, out): (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) (directory / 'eula.txt').write_text('eula=true\n') command = server_command(kind, directory, args) + if args.nice: + command = ['nice', '-n', str(args.nice), *command] started = time.time() - server = Server(command, directory, out / f'{kind}-{bots}.log') - result = {'server': kind, 'bots': bots} + server = Server(command, directory, out / f'{name}.log') + result = {'server': kind, 'bots': bots, 'behaviour': behaviour} try: server.wait_for(r'/INFO\]: Done \(', 600) result['start_seconds'] = round(time.time() - started, 2) + # Every bot appears on the world spawn itself, not spread around it, so both servers see the same paths. + server.console('gamerule respawn_radius 0') time.sleep(5) - report = out / f'{kind}-{bots}-bots.json' + report = out / f'{name}-bots.json' total = bots * args.join_every + args.warmup + args.seconds + # The summary comes back on stdout after the per-second lines, so it works over ssh too. bot_process = subprocess.Popen( - [BIN / f'horizon-bots{EXE}', '--server', f'127.0.0.1:{port}', '--bots', str(bots), - '--behaviour', args.behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)), - '--seed', str(args.seed), '--report', report], + [*bots_command(args), '--server', f'{args.connect}:{port}', '--bots', str(bots), + '--behaviour', behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)), + '--seed', str(args.seed), '--report', '-'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) bot_lines = [] threading.Thread(target=lambda: bot_lines.extend(bot_process.stdout), daemon=True).start() @@ -229,11 +248,27 @@ def run_once(kind, bots, args, out): if (t := tick_query(server)) is not None: ticks.append(t) next_query = now + 5 - measured = [json.loads(l) for l in list(bot_lines) if l.startswith('{')] - window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else [] bot_process.wait(timeout=total + 120) - summary = json.loads(report.read_text()) if report.exists() else {} + time.sleep(0.5) + measured, rest = [], [] + for line in list(bot_lines): + try: + sample = json.loads(line) + except ValueError: + sample = None + if isinstance(sample, dict) and 't' in sample: + measured.append(sample) + else: + rest.append(line) + window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else [] + summary_text = ''.join(rest) + summary = json.loads(summary_text) if summary_text.strip() else {} + report.write_text(json.dumps(summary, indent=2) + '\n') mean = lambda xs: round(statistics.fmean(xs), 2) if xs else None + per_bot = summary.get('per_bot', []) + by_behaviour = {} + for b in per_bot: + by_behaviour.setdefault(b['behaviour'], []).append(b) result.update({ 'mspt': {k: mean([t[k] for t in ticks]) for k in ('average', 'p50', 'p95', 'p99')}, 'mspt_worst_p99': max((t['p99'] for t in ticks), default=None), @@ -242,6 +277,19 @@ def run_once(kind, bots, args, out): 'rss_mb': {'mean': mean([r / 1e6 for r in rss]), 'max': round(max(rss) / 1e6, 1) if rss else None}, 'cpu_percent': mean(cpu), 'chunks_per_second': mean([l['chunks_per_second'] for l in window]), + # Over the measured window: different chunks reaching the bots, chunks they had dropped and got + # again (walking back), and ticks the bots stood still waiting for their own chunk. + **({k + '_per_second': round((window[-1][k] - window[0][k]) / max(len(window) - 1, 1), 2) + for k in ('unique', 'forgotten', 'waited_ticks')} if len(window) > 1 else {}), + 'chunks_total': summary.get('chunks'), + # Per bot over the whole run: every chunk received, the different ones, and those sent again + # while the bot still held them. + 'chunks_per_bot': {k: mean([b['chunks'] for b in v]) for k, v in by_behaviour.items()}, + 'unique_chunks_per_bot': {k: mean([b['unique_chunks'] for b in v]) for k, v in by_behaviour.items()}, + 'resent': summary.get('resent'), + 'pulled_back': summary.get('pulled_back'), + 'moved_too_quickly': sum('moved too quickly!' in l for l in server.since(0)), + 'moved_wrongly': sum('moved wrongly!' in l for l in server.since(0)), 'bots_joined': summary.get('joined'), 'bots_failed': [b for b in summary.get('per_bot', []) if b.get('error')], 'tick_queries': len(ticks), @@ -257,23 +305,28 @@ def main(): parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0]) parser.add_argument('--servers', default='horizon,vanilla') parser.add_argument('--bots', default='1,10,25,50') - parser.add_argument('--behaviour', default='mixed') + parser.add_argument('--behaviour', default='walk,explore', help='one pass per behaviour (comma-separated)') parser.add_argument('--join-every', type=float, default=1.0) parser.add_argument('--warmup', type=int, default=60) parser.add_argument('--seconds', type=int, default=300) parser.add_argument('--seed', type=int, default=12345) parser.add_argument('--heap', default='4g', help='the Java heap, -Xms and -Xmx (vanilla)') parser.add_argument('--out', type=Path, default=None, help='the report (JSON)') + parser.add_argument('--nice', type=int, default=0, help='run the servers under nice -n N') + parser.add_argument('--bots-via', default='', help="a command prefix to run the bots elsewhere ('ssh host')") + parser.add_argument('--bots-bin', default='', help='horizon-bots (on the --bots-via machine)') + parser.add_argument('--connect', default='127.0.0.1', help='the address the bots reach the server at') args = parser.parse_args() out = lab.LOCAL / 'server-bench' out.mkdir(parents=True, exist_ok=True) runs = [] - for bots in [int(b) for b in args.bots.split(',')]: - for kind in args.servers.split(','): - print(f'{kind}, {bots} bots...', flush=True) - result = run_once(kind, bots, args, out) - runs.append(result) - print(json.dumps(result), flush=True) + for behaviour in args.behaviour.split(','): + for bots in [int(b) for b in args.bots.split(',')]: + for kind in args.servers.split(','): + print(f'{kind}, {bots} {behaviour} bots...', flush=True) + result = run_once(kind, bots, behaviour, args, out) + runs.append(result) + print(json.dumps(result), flush=True) report = { 'kind': 'horizon-server-benchmark', 'date': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), @@ -286,13 +339,16 @@ def main(): path = args.out or out / 'report.json' path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(report, indent=2) + '\n') - print(f'\n{"server":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} {"CPU %":>6} {"chunks/s":>8} {"joined":>6}') + print(f'\n{"server":8} {"pass":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} ' + f'{"CPU %":>6} {"chunks/s":>8} {"/bot":>6} {"resent":>6} {"pulled":>6} {"joined":>6}') for r in runs: if 'error' in r: - print(f'{r["server"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}') + print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}') continue - print(f'{r["server"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} {r["mspt"]["p95"]!s:>6} ' - f'{r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} {r["chunks_per_second"]!s:>8} ' + per_bot = r['chunks_per_bot'].get(r['behaviour']) + print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} ' + f'{r["mspt"]["p95"]!s:>6} {r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} ' + f'{r["chunks_per_second"]!s:>8} {per_bot!s:>6} {r["resent"]!s:>6} {r["pulled_back"]!s:>6} ' f'{r["bots_joined"]!s:>6}') print(f'\nWrote {path}') From 3cd26c6d0b249ca442dd3e2e7fc38cbcd70cf862 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:24:30 +0200 Subject: [PATCH 015/327] server_bench: --gamerule, more game rules for both servers Horizon has no locator bar yet, so equal-work runs turn vanilla's off (--gamerule locator_bar=false): its waypoint updates cost every move a pass over every other player. Co-Authored-By: Claude Opus 5.5 --- tools/server_bench.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/server_bench.py b/tools/server_bench.py index 91f11a7ad..e50a49e64 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -219,6 +219,8 @@ def run_once(kind, bots, behaviour, args, out): result['start_seconds'] = round(time.time() - started, 2) # Every bot appears on the world spawn itself, not spread around it, so both servers see the same paths. server.console('gamerule respawn_radius 0') + for rule in filter(None, args.gamerule.split(',')): + server.console('gamerule ' + rule.replace('=', ' ')) time.sleep(5) report = out / f'{name}-bots.json' total = bots * args.join_every + args.warmup + args.seconds @@ -310,6 +312,9 @@ def main(): parser.add_argument('--warmup', type=int, default=60) parser.add_argument('--seconds', type=int, default=300) parser.add_argument('--seed', type=int, default=12345) + parser.add_argument('--gamerule', default='', + help="more game rules for both servers, 'name=value,...' (locator_bar=false: Horizon has " + "no locator bar yet)") parser.add_argument('--heap', default='4g', help='the Java heap, -Xms and -Xmx (vanilla)') parser.add_argument('--out', type=Path, default=None, help='the report (JSON)') parser.add_argument('--nice', type=int, default=0, help='run the servers under nice -n N') From 75ee9a3299cb76a80325f0481690ef48eec93ccd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:35:24 +0200 Subject: [PATCH 016/327] Build a saved chunk's structure starts when it loads, not on the game thread A loaded world had none of its structure starts in the generator's cache. The first time natural spawning (or anything else) asked which structures hold a position in a chunk referencing a village, the game thread built the village start: 60 to 120 ms in one tick, once right after the world opened and again a few ticks later for the next start (#489). Vanilla reads the starts with the chunk. The streaming worker that loads a saved chunk now builds the starts it references into the same cache, so the game thread finds them there. The starts are the same: the same function builds them from the same seed and chunk, only earlier and on a worker. The cache now keeps the first starts built for a chunk when two threads build them at once, so every user shares one start and its pieces' placement state, as vanilla's single StructureStart does. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/save.rs | 3 +++ crates/horizon-client/src/streaming.rs | 8 +++++++- crates/horizon-client/src/vanillagen.rs | 13 +++++++++++++ .../src/worldgen/generator_structures.rs | 5 +++-- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index a8553e276..79e0ec396 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2784,6 +2784,9 @@ impl ChunkGenerator for Persistent { chunk.entities = self.save.load_entities(x, z); Some(chunk) } + fn prepare_loaded(&self, worker: &mut G::Worker, chunk: &Chunk) { + self.inner.prepare_loaded(worker, chunk); + } fn proto(&self, worker: &mut G::Worker, x: i32, z: i32) -> crate::streaming::Proto { let mut proto = self.inner.proto(worker, x, z); if let Some(saved) = self diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 994316324..1754f1550 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -36,6 +36,9 @@ pub trait ChunkGenerator: Send + Sync + 'static { fn load(&self, _x: i32, _z: i32) -> Option { None } + /// What a loaded chunk needs from the generator before the game uses it, + /// on the worker that loaded it. + fn prepare_loaded(&self, _worker: &mut Self::Worker, _chunk: &Chunk) {} fn proto(&self, worker: &mut Self::Worker, x: i32, z: i32) -> Proto; fn decorates(&self) -> bool { false @@ -369,7 +372,10 @@ impl Streaming { }; let done = match job { Job::Generate(x, z) => match generator.load(x, z) { - Some(chunk) => Done::Generated(chunk), + Some(chunk) => { + generator.prepare_loaded(&mut worker, &chunk); + Done::Generated(chunk) + } None => { let proto = generator.proto(&mut worker, x, z); let decorated = generator.is_decorated(&proto); diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index fc18e8404..6f0c4edaf 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -265,6 +265,19 @@ impl ChunkGenerator for VanillaTerrain { fn worker(&self) -> GeneratorWorker { self.generator.worker() } + /// The structure starts a saved chunk references, as vanilla reads them + /// with the chunk: built here, on the loading worker, into the + /// generator's cache, rather than on the game thread the first time + /// spawning or a mob asks which structures hold a position (a village + /// start took 70 to 110 ms there, one tick each, after a world loaded). + fn prepare_loaded(&self, worker: &mut GeneratorWorker, chunk: &Chunk) { + let mut starts: Vec<(i32, i32)> = chunk.structure_refs.iter().map(|(_, at)| *at).collect(); + starts.sort_unstable(); + starts.dedup(); + for (x, z) in starts { + worker.structure_starts(ChunkPos::new(x, z)); + } + } fn proto(&self, worker: &mut GeneratorWorker, x: i32, z: i32) -> Proto { match worker.generate_proto(ChunkPos::new(x, z)) { Ok(chunk) => Box::new(VanillaProto::Ready(Box::new(chunk))), diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index f5487dc33..e78ce0772 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -229,8 +229,9 @@ impl StructureState { if cache.len() >= START_CACHE_LIMIT { cache.clear(); } - cache.insert((chunk.x, chunk.z), starts.clone()); - starts + // Another thread may have built the same starts meanwhile: everyone + // keeps the first, so placement state on its pieces is shared. + cache.entry((chunk.x, chunk.z)).or_insert(starts).clone() } /// ChunkGenerator.findNearestMapStructure: the nearest start of one of /// `names` from block `from` (rings: every ring chunk; random spreads: From c5851e77aa6bab2850e3f4692980e1b5ac3d564c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:42:27 +0200 Subject: [PATCH 017/327] horizon-bots: --explore-speed, for an explore pass with equal work Co-Authored-By: Claude Opus 5.5 --- crates/horizon-bots/src/main.rs | 15 ++++++++++++--- tools/server_bench.py | 10 ++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/horizon-bots/src/main.rs b/crates/horizon-bots/src/main.rs index 3eb15beec..090daeb4e 100644 --- a/crates/horizon-bots/src/main.rs +++ b/crates/horizon-bots/src/main.rs @@ -49,6 +49,7 @@ horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline m --seconds N how long to run after the first bot joins; default 60 --view-distance N what the bots ask for; default 10 --seed N default 12345 + --explore-speed B blocks a second an explore bot flies; default 22 (as fast as chunks come) --name PREFIX bot names: PREFIX0, PREFIX1...; default Bot --report FILE a JSON summary at the end (- prints it after the per-second lines) "; @@ -79,6 +80,7 @@ struct Options { seconds: u64, view_distance: i8, seed: u64, + explore_speed: f64, name: String, report: Option, } @@ -93,6 +95,7 @@ fn options() -> Result { seconds: 60, view_distance: 10, seed: 12345, + explore_speed: 22.0, name: "Bot".into(), report: None, }; @@ -116,6 +119,9 @@ fn options() -> Result { "--seconds" => o.seconds = value.parse().map_err(|_| number("seconds"))?, "--view-distance" => o.view_distance = value.parse().map_err(|_| number("2 to 32"))?, "--seed" => o.seed = value.parse().map_err(|_| number("a number"))?, + "--explore-speed" => { + o.explore_speed = value.parse().map_err(|_| number("blocks a second"))?; + } "--name" => o.name = value, "--report" => o.report = Some(value), _ => return Err(format!("unknown option {arg}; --help lists them")), @@ -521,9 +527,11 @@ fn run_bot( } } Behaviour::Explore => { - // Flying fast in creative: about 22 blocks a second, which keeps new chunks coming. - pos[0] += heading.cos() * 1.1; - pos[2] += heading.sin() * 1.1; + // Flying in creative, by default about 22 blocks a second, which keeps new + // chunks coming as fast as the server sends them. + let step = o.explore_speed / 20.0; + pos[0] += heading.cos() * step; + pos[2] += heading.sin() * step; } } } @@ -643,6 +651,7 @@ fn main() { "bots": o.bots, "behaviour": o.behaviour, "seed": o.seed, + "explore_speed": o.explore_speed, "view_distance": o.view_distance, "seconds": o.seconds, "joined": bots.iter().filter(|b| b.joined_after_ms.load(Ordering::SeqCst) > 0).count(), diff --git a/tools/server_bench.py b/tools/server_bench.py index e50a49e64..c79d6aab1 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -17,7 +17,9 @@ then measures for a while: The bots can run on another machine, so they don't take the server's CPU: `--bots-via 'ssh macmini'` with `--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19` -runs every server at the lowest priority (a shared machine). +runs every server at the lowest priority (a shared machine). The explore bots fly as fast as each server +sends them chunks, so a faster server gets more terrain to generate; `--explore-speed` slows them to a rate +both servers keep up with, for equal work. The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The Horizon side runs target/release/horizon-server with the engine beside it; build both first: @@ -228,7 +230,8 @@ def run_once(kind, bots, behaviour, args, out): bot_process = subprocess.Popen( [*bots_command(args), '--server', f'{args.connect}:{port}', '--bots', str(bots), '--behaviour', behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)), - '--seed', str(args.seed), '--report', '-'], + '--seed', str(args.seed), '--report', '-', + *(['--explore-speed', str(args.explore_speed)] if args.explore_speed else [])], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) bot_lines = [] threading.Thread(target=lambda: bot_lines.extend(bot_process.stdout), daemon=True).start() @@ -312,6 +315,9 @@ def main(): parser.add_argument('--warmup', type=int, default=60) parser.add_argument('--seconds', type=int, default=300) parser.add_argument('--seed', type=int, default=12345) + parser.add_argument('--explore-speed', type=float, default=0, + help='blocks a second the explore bots fly (default: the bots\' 22, as fast as chunks ' + 'come); a speed both servers keep up with makes the explore pass equal work') parser.add_argument('--gamerule', default='', help="more game rules for both servers, 'name=value,...' (locator_bar=false: Horizon has " "no locator bar yet)") From 1efc7f83d180f43838b8295c24ec5a28a83778b8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:55:41 +0200 Subject: [PATCH 018/327] Entity portal checks: skip the sweep where no section holds a portal Every tick, each item and mob that can use a portal sweeps the blocks its box passed through since the last tick, looking for a nether portal block (`Entity.checkInsideBlocks` reaching `NetherPortalBlock.entityInside`). Each sweep allocated a visited set and read every block of the path. Every block a sweep visits lies in the box covering the entity's box at both ends. When no section that box touches has a nether portal state in its palette, no visited block is a portal: the sweep is skipped. Sections are checked once per tick, and a box over more than 64 sections (an entity teleported far) is swept as before. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/nether_portal.rs | 67 ++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 01a657b0b..b40960712 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -481,9 +481,10 @@ impl Game<'_> { .filter(|m| self.mob_can_use_portal(m)) .map(|m| (m.id, m.position, m.width(), m.height())) .collect(); + let mut portal_sections = horizon_client::fast_hash::FxHashMap::default(); for (id, to, width, height) in items.into_iter().chain(mobs) { let from = self.portals.before.get(&id).copied().unwrap_or(to); - if let Some(pos) = self.swept_portal(from, to, width, height) { + if let Some(pos) = self.swept_portal(from, to, width, height, &mut portal_sections) { inside.push((id, pos)); } } @@ -497,7 +498,14 @@ impl Game<'_> { } /// The first nether portal block an entity box swept through /// (`Entity.checkInsideBlocks`, whose first portal sets the entry). - fn swept_portal(&self, from: Vec3, to: Vec3, width: f32, height: f32) -> Option { + fn swept_portal( + &self, + from: Vec3, + to: Vec3, + width: f32, + height: f32, + portal_sections: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>, + ) -> Option { let half = f64::from(width) / 2.0; let bounds = horizon_core::geometry::Aabb::new( Vec3::new(to.x - half, to.y, to.z - half), @@ -508,6 +516,13 @@ impl Game<'_> { f64::from(1.0e-5_f32), f64::from(1.0e-5_f32), )); + // Every block the sweep visits lies in the box covering both ends. + let reach = bounds + .union_bounds(bounds.move_by(from.subtract(to))) + .inflate(Vec3::new(1.0, 1.0, 1.0)); + if !self.may_hold_portal(reach, portal_sections) { + return None; + } let mut found = None; let _ = horizon_core::geometry::sweep_intersected_blocks( from, @@ -529,6 +544,54 @@ impl Game<'_> { ); found } + /// Whether a section `reach` touches has a nether portal state in its + /// palette: without one, no block there is a portal. Answers are kept + /// per section for the tick; a box over many sections is not checked. + fn may_hold_portal( + &self, + reach: horizon_core::geometry::Aabb, + seen: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>, + ) -> bool { + use horizon_client::chunk::{MIN_Y, SECTIONS}; + let (min, max) = (reach.min_position(), reach.max_position()); + if !min.is_finite() || !max.is_finite() { + return true; + } + let (min, max) = (BlockPos::containing(min), BlockPos::containing(max)); + let top = SECTIONS as i32 - 1; + let (x0, x1) = (min.x >> 4, max.x >> 4); + let (z0, z1) = (min.z >> 4, max.z >> 4); + let (y0, y1) = ( + ((min.y - MIN_Y) >> 4).clamp(0, top), + ((max.y - MIN_Y) >> 4).clamp(0, top), + ); + let count = (i64::from(x1) - i64::from(x0) + 1) + * (i64::from(y1) - i64::from(y0) + 1) + * (i64::from(z1) - i64::from(z0) + 1); + if count > 64 { + return true; + } + let behaviours = &self.res.behaviours; + let chunks = &self.world.chunks; + (x0..=x1).any(|cx| { + (z0..=z1).any(|cz| { + (y0..=y1).any(|sy| { + *seen.entry((cx, sy, cz)).or_insert_with(|| { + chunks + .get(&(cx, cz)) + .and_then(|c| c.sections.get(sy as usize)) + .is_some_and(|s| { + s.blocks.maybe_has(|v| { + behaviours + .portal_axis(horizon_world::registry::BlockStateId(v)) + .is_some() + }) + }) + }) + }) + }) + }) + } /// `Entity.teleportCrossDimension` away from the loaded dimension: the /// entity is saved and removed, and waits for its dimension to load. fn send_through_portal(&mut self, id: u32, entry: BlockPos) { From cceda07476b2b15f7638d5a5b25269dd8611ab86 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:57:42 +0200 Subject: [PATCH 019/327] Sculk: find a loaded chunk's sensors from its palettes, not every block When chunks arrive, the sculk index looks through them for sensors, shriekers and catalysts. It unpacked and tested all 4,096 blocks of every section that wasn't uniform: 10 to 18 ms in a tick after a world loaded, more over a larger render distance (#489). A section whose palette holds no sculk state has no sculk block, so it is passed over without reading its blocks; the others are scanned as before, and the same blocks are found. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/sculk.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 6701181e7..6901200f1 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -373,6 +373,14 @@ impl Game<'_> { let mut found = Vec::new(); for (s, section) in chunk.sections.iter().enumerate() { let y0 = MIN_Y + s as i32 * 16; + // Without a sculk state in its palette, no block of the section + // is one: most sections are passed over without reading a block. + if !section + .blocks + .maybe_has(|v| u16::try_from(v).is_ok_and(|v| self.kind_of_state(v) != 0)) + { + continue; + } if section.blocks.uniform().is_some() { // A uniform section of sculk blocks does not exist. continue; From ed09e757baafff66547f14945f3e7ae46a7e30df Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:57:47 +0200 Subject: [PATCH 020/327] Pathfinder: hash nodes with the Fx hasher, and work out each path type once Path searches (vanilla's PathFinder with WalkNodeEvaluator) were 14 % of the world tick with 80 villagers. Two costs vanilla doesn't have: - the node index and the per-query path type and collision caches used the standard SipHash; vanilla keys them by packed position in fastutil maps. They use the Fx hasher now (nothing iterates them, so no order changes); - a position's static path type (its block, the one below and up to 24 neighbours, `getPathTypeStatic`) was worked out again for every mob box that covered it. Vanilla caches the block part level-wide (`PathTypeCache`); the finder now remembers each position's type for the query, during which the world doesn't change. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/path.rs | 30 +++++++++++++++++++------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/mobs/path.rs b/crates/horizon-client/src/mobs/path.rs index 368dead97..abadc9565 100644 --- a/crates/horizon-client/src/mobs/path.rs +++ b/crates/horizon-client/src/mobs/path.rs @@ -4,8 +4,8 @@ //! `AmphibiousNodeEvaluator`), ported rule for rule. use super::{MobWorld, data}; use crate::blocks::Fluid; +use crate::fast_hash::FxHashMap; use horizon_core::geometry::{Aabb, Vec3}; -use std::collections::HashMap; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PathType { @@ -301,10 +301,13 @@ pub struct Finder<'a, 'w> { mob: &'a PathMob, eval: Evaluator, nodes: Vec, - index: HashMap<(i32, i32, i32), u32>, + index: FxHashMap<(i32, i32, i32), u32>, heap: Vec, - types: HashMap<(i32, i32, i32), PathType>, - collisions: HashMap<[u64; 6], bool>, + types: FxHashMap<(i32, i32, i32), PathType>, + /// `path_type` of each position asked during this query: it reads up to + /// 26 blocks, and overlapping mob boxes ask for the same positions. + statics: std::cell::RefCell>, + collisions: FxHashMap<[u64; 6], bool>, entity_width: i32, entity_height: i32, entity_depth: i32, @@ -319,10 +322,11 @@ impl<'a, 'w> Finder<'a, 'w> { mob, eval, nodes: Vec::new(), - index: HashMap::new(), + index: FxHashMap::default(), heap: Vec::new(), - types: HashMap::new(), - collisions: HashMap::new(), + types: FxHashMap::default(), + statics: Default::default(), + collisions: FxHashMap::default(), entity_width: (mob.width + 1.0).floor() as i32, entity_height: (mob.height + 1.0).floor() as i32, entity_depth: (mob.width + 1.0).floor() as i32, @@ -385,7 +389,17 @@ impl<'a, 'w> Finder<'a, 'w> { } // --- path types ----------------------------------------------------- /// WalkNodeEvaluator.getPathTypeStatic (+ the fly/amphibious overrides). + /// The world doesn't change during a query, so each position's type is + /// worked out once. fn path_type(&self, x: i32, y: i32, z: i32) -> PathType { + if let Some(t) = self.statics.borrow().get(&(x, y, z)) { + return *t; + } + let t = self.compute_path_type(x, y, z); + self.statics.borrow_mut().insert((x, y, z), t); + t + } + fn compute_path_type(&self, x: i32, y: i32, z: i32) -> PathType { match self.eval { Evaluator::Fly => self.fly_path_type(x, y, z), Evaluator::Amphibious { .. } => { @@ -991,7 +1005,7 @@ impl<'a, 'w> Finder<'a, 'w> { let malus = |s: &Self, n: Option| n.is_some_and(|n| s.nodes[n as usize].cost_malus >= 0.0); // Direction.values(): down, up, north, south, west, east. - let mut by_dir: HashMap<(i32, i32, i32), Option> = HashMap::new(); + let mut by_dir: FxHashMap<(i32, i32, i32), Option> = FxHashMap::default(); for (dx, dy, dz) in [ (0, -1, 0), (0, 1, 0), From cfcf69f0b98c42a8fc41e336fd6d7ec1c9328b41 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 06:29:17 +0200 Subject: [PATCH 021/327] Network client: apply the block entity data, difficulty, spawn, chunk centre, tick rate, animations and server data the server sends With single player on its server thread, the window is the server's client and dropped several packets the in-frame game never needed: - ClientboundBlockEntityDataPacket and the block entities of chunk packets: the block entity of that type loads the tag (signs, spawners), as handleBlockEntityData and LevelChunk.replaceWithPacketData do. - ClientboundChangeDifficultyPacket: the level data's difficulty and lock. - ClientboundSetDefaultSpawnPositionPacket: the respawn data spawn compasses point at. - ClientboundSetChunkCacheCenterPacket: ClientChunkCache's view centre; columns outside the storage (the server's radius + 3) are ignored or dropped, as ClientChunkCache.Storage does. - ClientboundAnimatePacket: wake up, and the critical and magic critical hit emitters. - ClientboundTickingStatePacket / ClientboundTickingStepPacket (new in the protocol crate): the level's TickRateManager. A frozen level holds its time and non-player entities, and the server's rate only ever slows the client timer down (Minecraft.getTickTargetMillis). - ClientboundServerDataPacket: the server list entry keeps a valid icon (ServerList.saveSingleServer); single player has no entry. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/clock.rs | 40 +++- crates/horizon-client/src/game/remote.rs | 195 +++++++++++++++++++- crates/horizon-client/src/multiplayer.rs | 8 + crates/horizon-protocol/src/packets/play.rs | 15 ++ 4 files changed, 249 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 865a348bc..accf07fc9 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -298,6 +298,9 @@ pub struct FixedStep { tick_times: [i64; SAMPLES], aggregated: i64, tick_count: i64, + /// A server's client: its level's tick rate only slows the timer down + /// (`Minecraft.getTickTargetMillis`), since the server runs the ticks. + client: bool, } impl Default for FixedStep { @@ -312,11 +315,20 @@ impl Default for FixedStep { tick_times: [0; SAMPLES], aggregated: 0, tick_count: 0, + client: false, } } } impl FixedStep { + /// The clock of a client connected to a server: the `ClientLevel`'s + /// `TickRateManager`, set by the server's ticking packets. + pub fn client() -> Self { + Self { + client: true, + ..Self::default() + } + } fn now_ms(&self) -> i64 { self.now.as_millis() as i64 } @@ -341,9 +353,14 @@ impl FixedStep { } let runs = self.manager.base.runs_normally(); let mspt = self.manager.base.milliseconds_per_tick(); + let client = self.client; let ticks = self .timer - .advance_game_time(now_ms, |default| if runs { mspt } else { default }); + .advance_game_time(now_ms, |default| match (runs, client) { + (true, true) => default.max(mspt), + (true, false) => mspt, + (false, _) => default, + }); ticks.clamp(0, 10) as u32 } /// Restart pacing from now (after loading, so no backlog replays). @@ -400,6 +417,10 @@ impl FixedStep { pub fn set_frozen(&mut self, frozen: bool) { self.manager.base.set_frozen(frozen); } + /// `TickRateManager.setFrozenTicksToRun` (ClientboundTickingStepPacket). + pub fn set_frozen_ticks_to_run(&mut self, ticks: i32) { + self.manager.base.set_frozen_ticks_to_run(ticks); + } pub fn sprinting(&self) -> bool { self.manager.is_sprinting() } @@ -484,4 +505,21 @@ mod tests { m.base.tick(); assert!(!m.base.runs_normally()); } + #[test] + fn a_servers_tick_rate_only_slows_its_client_down() { + let quarter = std::time::Duration::from_millis(250); + let mut client = FixedStep::client(); + client.set_rate(40.0); + assert_eq!(client.advance(quarter), 5, "still 20 a second"); + let mut slow = FixedStep::client(); + slow.set_rate(10.0); + assert_eq!(slow.advance(quarter * 2), 5, "10 a second"); + let mut local = FixedStep::default(); + local.set_rate(40.0); + assert_eq!( + local.advance(quarter), + 10, + "the integrated loop runs at the rate" + ); + } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 6fc342a96..a30f1ce29 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -132,6 +132,8 @@ pub(super) struct Remote { decode_errors: u32, clock: Option, clock_rate: f32, + /// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket). + chunk_center: (i32, i32), } fn face_direction(face: [i32; 3]) -> u8 { @@ -307,7 +309,10 @@ impl Game<'_> { decode_errors: 0, clock: None, clock_rate: 1.0, + chunk_center: (0, 0), }); + // The level's TickRateManager follows the server's ticking packets. + self.clock = horizon_client::clock::FixedStep::client(); Ok(()) } @@ -330,6 +335,7 @@ impl Game<'_> { None => false, }; horizon_client::crash::clear_detail("Server"); + self.clock = Default::default(); self.debug_charts.reset(); self.tab_list.reset(); self.score.board = Default::default(); @@ -580,6 +586,8 @@ impl Game<'_> { r.entities.clear(); r.lerps.clear(); r.pending_items.clear(); + // A new ClientLevel: a new chunk storage, centred on 0, 0. + r.chunk_center = (0, 0); } if let Some(renderer) = self.renderer.as_mut() { renderer.clear_sections(); @@ -656,6 +664,128 @@ impl Game<'_> { } Ok(chunk) } + /// `ClientChunkCache.Storage.inRange`: within the storage around the + /// view centre, `calculateStorageRange` (the server's radius, at least + /// two, plus three) chunks each way. + fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool { + self.remote.as_ref().is_none_or(|r| { + let range = r.view_distance.max(2) + 3; + (x - r.chunk_center.0).abs() <= range && (z - r.chunk_center.1).abs() <= range + }) + } + /// The columns a moved or resized storage no longer holds. + fn drop_remote_chunks_out_of_range(&mut self) { + let gone: Vec<(i32, i32)> = self + .world + .chunks + .keys() + .copied() + .filter(|&(x, z)| !self.remote_chunk_in_range(x, z)) + .collect(); + for (x, z) in gone { + self.streaming.forget(&mut self.world, x, z); + self.world + .block_entities + .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + if let Some(renderer) = self.renderer.as_mut() { + for sy in 0..SECTIONS as i32 { + renderer.remove((x, sy, z)); + } + } + } + } + /// `handleBlockEntityData`: the block entity at `pos`, when it is of the + /// packet's type, loads the tag (`loadWithComponents`); an empty tag + /// changes nothing. + fn remote_block_entity_data(&mut self, pos: [i32; 3], kind: i32, tag: &Tag) { + let key = (pos[0], pos[1], pos[2]); + let Some(name) = self + .remote + .as_ref() + .and_then(|r| r.builtin.get("minecraft:block_entity_type")?.name(kind)) + else { + return; + }; + let Some(entity) = self.world.block_entities.get(&key) else { + return; + }; + let Tag::Compound(fields) = tag else { + return; + }; + if entity.id() != name || fields.is_empty() { + return; + } + let mut full = fields.clone(); + full.insert("id".into(), Tag::String(name.into())); + for (k, v) in ["x", "y", "z"].into_iter().zip(pos) { + full.insert(k.into(), Tag::Int(v)); + } + if let Some((_, loaded)) = horizon_client::save::decode_block_entity(&Tag::Compound(full)) { + self.world.block_entities.insert(key, loaded); + // The section is drawn again with what the block entity shows. + let state = self.world.block(pos[0], pos[1], pos[2]); + let _ = self.world.set(pos[0], pos[1], pos[2], state); + } + } + /// `handleAnimate`: a player wakes up, or an entity gets the critical + /// hit (`CRIT`) or magic critical hit (`ENCHANTED_HIT`) emitter. + fn remote_animate(&mut self, id: i32, action: u8) { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let me = self.remote.as_ref().is_some_and(|r| r.entity_id == id); + let body = if me { + self.player.as_ref().map(|p| { + let d = p.dimensions; + ( + [p.position.x, p.position.y, p.position.z], + f64::from(d.width), + f64::from(d.height), + ) + }) + } else { + self.mobs.iter().find(|m| m.id == id as u32).map(|m| { + ( + [m.position.x, m.position.y, m.position.z], + m.kind.width, + m.kind.height, + ) + }) + }; + let Some((feet, width, height)) = body else { + return; + }; + let particle = match action { + // Player.stopSleepInBed. + 0 => { + if me { + self.sleeping = None; + } + return; + } + 1 => ParticleType::Crit, + 2 => ParticleType::EnchantedHit, + _ => return, + }; + self.particles + .tracking_emitter(ParticleOptions::simple(particle), feet, width, height); + } + /// `handleServerData`: the server list entry of the server joined keeps + /// the icon the server sends (`ServerList.saveSingleServer`). Single + /// player has no entry. + fn remote_server_data(&mut self, icon: Option<&[u8]>) { + let (Some(r), Some(png)) = (self.remote.as_ref(), icon) else { + return; + }; + if self.integrated.is_some() { + return; + } + if let Ok(dir) = std::env::current_dir() { + horizon_client::multiplayer::save_server_icon( + &dir.join("saves"), + &r.session.address, + png, + ); + } + } /// Keep the renderable block entities (chests, furnaces) in step with blocks. fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { let name = self.res.facts.get(state).name.clone(); @@ -921,6 +1051,15 @@ impl Game<'_> { }) .clamp(-90.0, 90.0); } + // ClientChunkCache.replaceWithPacketData: a column outside the + // storage around the view centre is ignored. + C::LevelChunkWithLight(p) if !self.remote_chunk_in_range(p.x, p.z) => { + log::warn!( + "Ignoring chunk since it's not in the view range: {}, {}", + p.x, + p.z + ); + } C::LevelChunkWithLight(p) => match self.remote_chunk(&p) { Ok(chunk) => { let (x, z) = (p.x, p.z); @@ -936,6 +1075,8 @@ impl Game<'_> { ); let state = self.world.block(pos.0, pos.1, pos.2); self.sync_block_entity(pos, state); + // LevelChunk.replaceWithPacketData: the block entity loads its update tag. + self.remote_block_entity_data([pos.0, pos.1, pos.2], info.kind, &info.tag); } } Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z), @@ -1220,7 +1361,7 @@ impl Game<'_> { m.health = 0.0; } } - C::Animate(p) if p.action == 0 => {} + C::Animate(p) => self.remote_animate(p.id, p.action), C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -1549,7 +1690,34 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.view_distance = p.distance; } + // ClientChunkCache.updateViewRadius: a new storage of that size. + self.drop_remote_chunks_out_of_range(); } + C::SetChunkCacheCenter(p) => { + if let Some(r) = self.remote.as_mut() { + r.chunk_center = (p.x, p.z); + } + self.drop_remote_chunks_out_of_range(); + } + C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag), + // handleChangeDifficulty: the level data's difficulty and lock. + C::ChangeDifficulty(p) => { + self.ui.difficulty = p.difficulty.clamp(0, 3) as u8; + self.level.difficulty_locked = p.locked; + } + // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. + C::SetDefaultSpawnPosition(p) => { + let [x, y, z] = p.pos.pos; + self.spawn = (p.pos.dimension == "minecraft:overworld") + .then(|| Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5)); + } + C::ServerData(p) => self.remote_server_data(p.icon.as_deref()), + // handleTickingState / handleTickingStep: the level's TickRateManager. + C::TickingState(p) => { + self.clock.set_rate(p.rate); + self.clock.set_frozen(p.frozen); + } + C::TickingStep(p) => self.clock.set_frozen_ticks_to_run(p.steps), C::SetActionBarText(p) | C::SetTitleText(p) => { let lang = self .remote @@ -1881,10 +2049,15 @@ impl Game<'_> { /// One client tick while connected (Minecraft.tick with a ClientLevel). pub(super) fn tick_remote(&mut self) -> Result<()> { self.ticks += 1; - self.world.game_time += 1; - let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate); - if rate > 0.0 { - self.world.day_time += rate.round() as i64; + // Minecraft.tick: TickRateManager.tick; ClientLevel.tick advances + // the time only while the level runs normally. + let running = self.clock.world_runs(); + if running { + self.world.game_time += 1; + let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate); + if rate > 0.0 { + self.world.day_time += rate.round() as i64; + } } // Weather levels drift toward their targets between server updates. let w = &mut self.world.weather; @@ -1895,7 +2068,7 @@ impl Game<'_> { } // ClientLevel.tick: the border's size change. self.border.tick(); - self.tick_remote_entities(); + self.tick_remote_entities(running); // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. self.tick_block_entity_anims(); self.tick_hand(); @@ -2005,12 +2178,18 @@ impl Game<'_> { self.send(S::ClientTickEnd(Empty)); Ok(()) } - fn tick_remote_entities(&mut self) { + /// ClientLevel.tickEntities; a frozen level only ticks the players + /// (`TickRateManager.isEntityFrozen`). + fn tick_remote_entities(&mut self, running: bool) { let Some(r) = self.remote.as_mut() else { return; }; let mut lerps = std::mem::take(&mut r.lerps); + let players = &r.level_players; for m in &mut self.mobs { + if !running && !players.contains_key(&(m.id as i32)) { + continue; + } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; @@ -2048,7 +2227,7 @@ impl Game<'_> { horizon_client::mobs::rabbit::post_tick(m); } } - for d in &mut self.dropped { + for d in self.dropped.iter_mut().filter(|_| running) { d.previous = d.position; d.age += 1; if let Some(l) = lerps.get_mut(&(d.id as i32)) diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 60a5b2277..2228d32a2 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -204,6 +204,14 @@ fn save_icon(file: &Path, address: &str, icon: Option) { } } +/// `ClientPacketListener.handleServerData`: a valid icon the joined server +/// sends replaces the one its list entries keep. +pub fn save_server_icon(saves: &Path, address: &str, png: &[u8]) { + if icon_pixels(png).is_some() { + save_icon(&servers_file(saves), address, Some(crate::lan::base64(png))); + } +} + /// The address of list row `index`: the saved servers, then the LAN games. fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option { match servers.get(index) { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 1459f7d9f..cecbc098d 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -574,6 +574,14 @@ packet!( ); packet!(Text { text: Tag => Nbt }); packet!(SetChunkCacheCenter { x: i32 => VarInt, z: i32 => VarInt }); +packet!( + /// ClientboundTickingStatePacket: the tick rate and whether the level is frozen. + TickingState { rate: f32 => Float, frozen: bool => Bool } +); +packet!( + /// ClientboundTickingStepPacket: the ticks a frozen level runs (`/tick step`). + TickingStep { steps: i32 => VarInt } +); packet!(Distance { distance: i32 => VarInt }); packet!(SetCursorItem { item: Option => Slot }); packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); @@ -1062,6 +1070,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TabList(TabList) = TAB_LIST, TakeItemEntity(TakeItemEntity) = TAKE_ITEM_ENTITY, TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, + TickingState(TickingState) = TICKING_STATE, + TickingStep(TickingStep) = TICKING_STEP, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, }); @@ -1523,6 +1533,11 @@ mod tests { relatives: 0, on_ground: true, }), + Clientbound::TickingState(TickingState { + rate: 40.0, + frozen: true, + }), + Clientbound::TickingStep(TickingStep { steps: 7 }), ]; for p in packets { round_trip(p, Clientbound::encode, Clientbound::decode); From 6154eb95c345b3c78bd97c1ba3604e47755caa67 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 06:53:44 +0200 Subject: [PATCH 022/327] Network players keep advancements, statistics and a recipe book on the server Single player on its server thread, LAN guests and dedicated server players are network players, and the server gave them none of these: - PlayerAdvancements: each player's progress loads from and saves to players/advancements/.json (an integrated server's owner keeps single player's file). The game's triggers, awards and the advancement commands work on the player the game acts for (as_guest swaps the progress in), every tick runs the tick, location and inventory triggers, and flushDirty sends ClientboundUpdateAdvancementsPacket with what became visible or hidden and the progress that changed. A player who has been here gets their saved advancements in the first packet; a new one gets the same first tick as before. Announcements go to everyone (PlayerList.broadcastSystemMessage). - ServerStatsCounter: per-tick and movement statistics are counted for each player, saved to players/stats/.json, follow the scoreboard criteria under the player's name, and go out in ClientboundAwardStatsPacket when the client asks (REQUEST_STATS), all of them the first time. - ServerRecipeBook: the player file's recipeBook is kept, sent on joining (settings and every known recipe), and recipes unlocked later go out in ClientboundRecipeBookAddPacket. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/advancements.rs | 58 ++++ .../horizon-client/src/game/advancements.rs | 110 ++++---- crates/horizon-client/src/game/dedicated.rs | 7 + crates/horizon-client/src/game/lan.rs | 72 +++++ crates/horizon-client/src/game/lan_actions.rs | 58 ++++ crates/horizon-client/src/game/scoreboard.rs | 29 +- crates/horizon-client/src/game/stats.rs | 144 +++++++--- crates/horizon-client/src/lan/advancements.rs | 264 +++++++++++++----- crates/horizon-client/src/lan/guest.rs | 19 ++ crates/horizon-client/src/lan/hub.rs | 101 ++++++- crates/horizon-client/src/lan/playerdata.rs | 2 + 11 files changed, 683 insertions(+), 181 deletions(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 4a2666ded..22ffcc9d7 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -175,6 +175,53 @@ fn parse(id: &str, v: &Value) -> Option { }) } +/// `CriterionProgress`'s date as saved, "yyyy-MM-dd HH:mm:ss Z", in UTC. +pub fn date_text(unix_secs: i64) -> String { + let days = unix_secs.div_euclid(86400); + let rem = unix_secs.rem_euclid(86400); + // Civil from days (Howard Hinnant's algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} + +/// A saved date back to milliseconds since the epoch (the network form of +/// `CriterionProgress`), the zone offset applied. +pub fn date_millis(text: &str) -> Option { + let (date, rest) = text.trim().split_once(' ')?; + let (time, zone) = rest.split_once(' ').unwrap_or((rest, "+0000")); + let mut d = date.split('-').map(|v| v.parse::().ok()); + let (y, m, day) = (d.next()??, d.next()??, d.next()??); + let mut t = time.split(':').map(|v| v.parse::().ok()); + let (h, min, sec) = (t.next()??, t.next()??, t.next()??); + let sign = if zone.starts_with('-') { -1 } else { 1 }; + let zone = zone.trim_start_matches(['+', '-']); + let offset = + zone.get(0..2)?.parse::().ok()? * 3600 + zone.get(2..4)?.parse::().ok()? * 60; + // Days from civil (Howard Hinnant's algorithm). + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some((days * 86400 + h * 3600 + min * 60 + sec - sign * offset) * 1000) +} + /// The player's progress: advancement -> criterion -> obtained date. #[derive(Default, Clone)] pub struct Progress { @@ -1059,4 +1106,15 @@ mod tests { assert_eq!(l[4], Some((1, 2.0))); assert_eq!(l[1], Some((2, 2.0))); } + #[test] + fn saved_dates_read_back_to_their_instant() { + for secs in [0, 951_782_400, 1_792_216_800, 4_107_542_399] { + assert_eq!(date_millis(&date_text(secs)), Some(secs * 1000)); + } + assert_eq!( + date_millis("2026-10-17 07:30:00 +0200"), + date_millis("2026-10-17 05:30:00 +0000") + ); + assert_eq!(date_millis("not a date"), None); + } } diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 980b5769e..bd9689f3f 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -11,7 +11,7 @@ use horizon_client::{ }; use serde_json::Value; use std::{ - collections::{BTreeMap, VecDeque}, + collections::{BTreeMap, BTreeSet, VecDeque}, sync::Arc, time::Instant, }; @@ -78,7 +78,13 @@ pub(super) struct AdvState { /// Awards skip the toast (`/advancement grant ... everything`). pub(super) quiet: bool, /// The inventory last seen by `inventory_changed`. - last_inventory: u64, + pub(super) last_inventory: u64, + /// While the game acts for a network player (`as_guest`): the + /// advancements whose progress changed (`progressChanged`), the recipes + /// unlocked and the announcements, for their client and everyone's. + pub(super) changed: BTreeSet, + pub(super) unlocked: Vec, + pub(super) announced: Vec, } /// The game's world for predicates. struct View<'a, 'g>(&'a Game<'g>); @@ -171,29 +177,10 @@ impl adv::World for View<'_, '_> { } } fn now_text() -> String { - // "yyyy-MM-dd HH:mm:ss Z" in UTC. let secs = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()) as i64; - let days = secs.div_euclid(86400); - let rem = secs.rem_euclid(86400); - // Civil from days (Howard Hinnant's algorithm). - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if m <= 2 { y + 1 } else { y }; - format!( - "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000", - rem / 3600, - rem % 3600 / 60, - rem % 60 - ) + adv::date_text(secs) } impl Game<'_> { /// `ItemPredicate.test` (the `item_filter` of a filtered item modifier). @@ -217,30 +204,30 @@ pub(super) fn item_view(s: &ItemStack) -> ItemView { } impl Game<'_> { fn adv_path(&self) -> Option { - let uuid = self.level.player_uuid?; - let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - let text = format!( - "{}-{}-{}-{}-{}", - &hex[0..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..32] - ); - Some( - self.world_root - .join("players/advancements") - .join(format!("{text}.json")), - ) + Some(super::stats::player_json( + &self.world_root, + "advancements", + self.level.player_uuid?, + )) } - pub(super) fn load_advancements(&mut self) { - if self.adv.loaded || self.remote.is_some() { - return; - } - self.adv.loaded = true; + /// A server with no player of its own and nobody it acts for: there is + /// no player for advancements and statistics. + pub(super) fn no_player_here(&self) -> bool { + self.options.dedicated.is_some() && self.lan_acting.is_none() + } + /// The advancement tree, loaded once. + pub(super) fn advancement_tree(&mut self) -> Arc { if self.adv.tree.list.is_empty() { self.adv.tree = Arc::new(Tree::load(&self.options.resources.join("data"))); } + self.adv.tree.clone() + } + pub(super) fn load_advancements(&mut self) { + if self.adv.loaded || self.remote.is_some() || self.no_player_here() { + return; + } + self.adv.loaded = true; + self.advancement_tree(); let progress = self .adv_path() .and_then(|p| std::fs::read_to_string(p).ok()) @@ -254,7 +241,7 @@ impl Game<'_> { self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect(); } pub(super) fn save_advancements(&self) { - if !self.adv.loaded || self.remote.is_some() { + if !self.adv.loaded || self.remote.is_some() || self.no_player_here() { return; } let Some(path) = self.adv_path() else { @@ -376,7 +363,7 @@ impl Game<'_> { /// `SimpleCriterionTrigger.trigger`: test each open criterion of the /// trigger and award what it completes. pub(super) fn trigger(&mut self, name: &str, test: impl Fn(&Value, &dyn adv::World) -> bool) { - if self.remote.is_some() { + if self.remote.is_some() || self.no_player_here() { return; } self.load_advancements(); @@ -403,15 +390,27 @@ impl Game<'_> { let a = &tree.list[ai]; let was = self.adv.progress.done(a); self.adv.progress.grant(&a.id, &a.criteria[ci].name, &date); + self.progress_changed(ai); if !was && self.adv.progress.done(a) { self.award(ai); } } } + /// `PlayerAdvancements.progressChanged`, kept for a network player's client. + fn progress_changed(&mut self, index: usize) { + if self.lan_acting.is_some() { + self.adv.changed.insert(index); + } + } /// After `ServerRecipeBook.addRecipes`: the toast and the /// `recipe_unlocked` trigger of each recipe now known. pub(super) fn recipe_unlocked(&mut self, unlocked: &[String]) { - self.recipe_toast(unlocked); + if self.lan_acting.is_some() { + // A network player's client gets them in ClientboundRecipeBookAddPacket. + self.adv.unlocked.extend_from_slice(unlocked); + } else { + self.recipe_toast(unlocked); + } for r in unlocked { let r = r.clone(); self.trigger("minecraft:recipe_unlocked", move |c, _| { @@ -453,7 +452,8 @@ impl Game<'_> { } } if let Some(d) = &a.display { - if d.show_toast && !self.adv.quiet { + // A network player's client shows its own toast. + if d.show_toast && !self.adv.quiet && self.lan_acting.is_none() { self.adv.toasts.push_back(Toast { icon: d.icon.clone(), frame: d.frame, @@ -471,10 +471,18 @@ impl Game<'_> { Frame::Challenge => "chat.type.advancement.challenge", }; let name = adv_name(a); - self.system_message(Text::translate( - key, - &[Text::literal(super::chat::PLAYER_NAME), name], - )); + // PlayerList.broadcastSystemMessage: everyone hears of a + // network player's advancement. + match self.lan_acting_name.clone() { + Some(player) => self + .adv + .announced + .push(Text::translate(key, &[Text::literal(&player), name])), + None => self.system_message(Text::translate( + key, + &[Text::literal(super::chat::PLAYER_NAME), name], + )), + } } } self.recipe_unlocked(&unlocked); @@ -820,6 +828,7 @@ impl Game<'_> { let was = self.adv.progress.done(a); if self.adv.progress.grant(&a.id, c, &date) { changed = true; + self.progress_changed(index); if !was && self.adv.progress.done(a) { self.award(index); } @@ -831,6 +840,7 @@ impl Game<'_> { pub(super) fn revoke_advancement(&mut self, index: usize, criterion: Option<&str>) -> bool { let tree = self.adv.tree.clone(); let a = &tree.list[index]; + self.progress_changed(index); match criterion { Some(c) => self.adv.progress.revoke(&a.id, c), None => { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 314ac2428..18573682e 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -1073,6 +1073,13 @@ impl Game<'_> { for g in &h.hub.guests { horizon_client::lan::playerdata::save(g, &self.world_root); } + } + if let Some(h) = self.lan.as_ref() { + for g in &h.hub.guests { + self.save_guest_records(h, g); + } + } + if let Some(h) = self.lan.as_mut() { let conns: Vec = h.hub.guests.iter().map(|g| g.conn).collect(); for conn in conns { h.hub.kick( diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 1d00134e4..3fc959027 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -557,6 +557,75 @@ impl Game<'_> { } else { playerdata::save(guest, &self.world_root); } + self.save_guest_records(host, guest); + } + /// The file name of a player's advancements and statistics: an + /// integrated server's owner keeps single player's. + fn records_uuid(&self, host: &LanHost, uuid: u128) -> Option<[i32; 4]> { + if host.owner.as_ref().is_some_and(|o| o.uuid == uuid) { + self.level.player_uuid + } else { + Some(playerdata::uuid_ints(uuid)) + } + } + /// `PlayerAdvancements.save` and `ServerStatsCounter.save` of a network player. + pub(super) fn save_guest_records( + &self, + host: &LanHost, + guest: &horizon_client::lan::guest::Guest, + ) { + if !guest.placed || self.adv.tree.list.is_empty() { + return; + } + let Some(uuid) = self.records_uuid(host, guest.uuid) else { + return; + }; + let path = super::stats::player_json(&self.world_root, "advancements", uuid); + let json = guest + .advancements + .to_json(&self.adv.tree, horizon_world::DATA_VERSION); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(text) = serde_json::to_string_pretty(&json) { + let _ = std::fs::write(path, text); + } + if let Some(play) = host.play.get(&guest.conn) { + play.stats + .write(&super::stats::player_json(&self.world_root, "stats", uuid)); + } + } + /// `PlayerAdvancements.load` and `ServerStatsCounter.parseLocal` of a + /// network player who joined; every statistic goes out on the first + /// request (`PlayerList.placeNewPlayer`'s `markAllDirty`). + fn load_guest_records(&mut self, host: &mut LanHost, conn: u32) { + let Some(uuid) = host + .hub + .guest(conn) + .and_then(|g| self.records_uuid(host, g.uuid)) + else { + return; + }; + let tree = self.advancement_tree(); + let path = super::stats::player_json(&self.world_root, "advancements", uuid); + let saved = std::fs::read_to_string(path) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()); + if let Some(g) = host.hub.guest_mut(conn) + && let Some(json) = saved + { + let mut progress = horizon_client::advancements::Progress::from_json(&json); + // PlayerAdvancements.applyFrom: advancements this server lacks are dropped. + progress + .criteria + .retain(|id, _| tree.by_id.contains_key(id)); + g.advancements = progress; + g.advancements_loaded = true; + } + let mut stats = + super::stats::Stats::read(&super::stats::player_json(&self.world_root, "stats", uuid)); + stats.mark_all_dirty(); + host.play.entry(conn).or_default().stats = stats; } /// The integrated server's owner into the world's player, for `Level::write`. pub(super) fn store_owner(&mut self) { @@ -568,6 +637,7 @@ impl Game<'_> { }; if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) { playerdata::store(g, &mut self.level); + self.save_guest_records(host, g); } } @@ -756,6 +826,7 @@ impl Game<'_> { self.lan_crafting_left(&mut host, &mut guest); self.save_guest(&host, &guest); host.models.remove(&guest.conn); + host.play.remove(&guest.conn); if self.options.dedicated.is_some() && guest.placed { super::dedicated::log( "INFO", @@ -820,6 +891,7 @@ impl Game<'_> { g.health = 20.0; g.food = 20; } + self.load_guest_records(host, conn); let mut ctx = TickCtx { world: &mut self.world, host: state, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ec4ac6cee..716bd6ae0 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -51,6 +51,9 @@ pub(super) struct GuestPlay { pub(super) crafting: super::lan_crafting::GuestCrafting, /// What the guest's body was given for its effects and enchantments. potions: super::potions::BodyPotions, + /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. + pub(super) stats: super::stats::Stats, + last_inventory: u64, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -165,6 +168,15 @@ impl Game<'_> { let host_ender = self.ender_open; self.close_ender_chest(); std::mem::swap(&mut self.ender_items, &mut g.ender_items); + // The guest's advancements, recipe book and statistics. + self.advancement_tree(); + std::mem::swap(&mut self.adv.progress, &mut g.advancements); + std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); + std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); + std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); + std::mem::swap(&mut self.stats, &mut play.stats); + let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); + let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory); self.lan_acting = Some(conn); self.lan_acting_name = Some(g.name.clone()); self.lan_acting_uuid = Some(g.uuid); @@ -200,6 +212,15 @@ impl Game<'_> { } let g = &mut host.hub.guests[i]; 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); + std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); + std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); + std::mem::swap(&mut self.stats, &mut play.stats); + self.adv.loaded = adv_loaded; + play.last_inventory = std::mem::replace(&mut self.adv.last_inventory, last_inventory); + let stat_events = std::mem::take(&mut play.stats.events); + let name = g.name.clone(); self.potions.swap_player(&mut g.effects, &mut play.potions); if let Some(key) = host_ender { self.world @@ -244,6 +265,7 @@ impl Game<'_> { host.hub.set_game_mode(conn, new_mode); } host.play.insert(conn, play); + self.stat_criteria_changed(&name, stat_events); if let Some(pos) = opened && !self.lan_open_container(host, conn, pos) && !host.hub.guests[i].spectator() @@ -578,6 +600,15 @@ impl Game<'_> { self.guest_suggestions(host, conn, &payload); } S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn), + // ServerStatsCounter.sendStats. + S::ClientCommand(c) if c.action == 1 => { + let stats = host + .play + .get_mut(&conn) + .map(|p| p.stats.take_dirty()) + .unwrap_or_default(); + host.hub.send_stats(conn, &stats); + } S::PickItemFromBlock(p) => { let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); let item = self.res.facts.get(state).item.clone(); @@ -848,6 +879,7 @@ impl Game<'_> { /// Per tick, for every guest: dig, use items, pick up drops, die. pub(super) fn tick_guests(&mut self, host: &mut LanHost) { self.lan_merchant_tick(host); + self.announce_guest_advancements(host); let conns: Vec = host .hub .guests @@ -891,6 +923,14 @@ impl Game<'_> { } self.guest_delayed_destroy(host, conn); self.guest_server_tick(host, conn); + // Player.tick's statistics and ServerPlayer.tick's triggers, then + // PlayerAdvancements.flushDirty. + let sleeping = host.hub.guests[gi].sleeping; + self.as_guest(host, conn, |g| { + g.count_tick_stats(sleeping); + g.tick_advancements(); + }); + host.hub.flush_progress(conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); let g = &mut host.hub.guests[gi]; @@ -909,6 +949,18 @@ impl Game<'_> { } } + /// `PlayerList.broadcastSystemMessage` of the advancements guests made + /// (their own actions, commands and ticks). + fn announce_guest_advancements(&mut self, host: &mut LanHost) { + for text in std::mem::take(&mut self.adv.announced) { + host.hub + .system_message(horizon_client::lan::data::component_nbt(&text.component())); + if self.options.dedicated.is_none() { + self.system_message(text); + } + } + } + /// The guest's body on the server each tick: ServerPlayer.tick's damage /// clock and Entity.baseTick's fluid phase (burning), then for each move /// the guest made ServerGamePacketListenerImpl.handleMovePlayer's jump @@ -956,6 +1008,7 @@ impl Game<'_> { w.player.health.advance_clock(); let _ = w.fluid_base_tick(); w.player.ground.on_ground = from_ground; + let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect(); for (moved, on_ground) in moves { let movement = Vec3::new(moved[0], moved[1], moved[2]); if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 { @@ -980,6 +1033,11 @@ impl Game<'_> { let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); let mut events = std::mem::take(&mut w.player.events); + // ServerGamePacketListenerImpl.handleMovePlayer: + // Player.checkMovementStatistics for each move. + for d in travelled { + game.movement_stats(Vec3::new(d[0], d[1], d[2])); + } // LivingEntity.baseTick ends with tickEffects. game.tick_mob_effects(); let Some(player) = game.player.as_mut() else { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 16297e930..7f92741a4 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -303,20 +303,33 @@ impl Game<'_> { // ---- criteria ---------------------------------------------------------- + /// `ServerStatsCounter.setValue`'s scoreboard side: the objectives of + /// each changed statistic's criteria follow it for the player `name`. + pub(super) fn stat_criteria_changed( + &mut self, + name: &str, + events: Vec<(String, String, Option)>, + ) { + let board = &mut self.score.board; + if board.objectives.is_empty() { + return; + } + for (ty, key, amount) in events { + let criteria = sb::stat_criteria(&ty, &key); + if board.has_objectives_for(&criteria) { + board.for_all_objectives(&criteria, name, |v| { + amount.map_or(0, |n| v.wrapping_add(n)) + }); + } + } + } /// `ServerPlayer.doTick` score updates and the statistic criteria. pub(super) fn tick_scoreboard(&mut self) { self.load_scoreboard(); let events = std::mem::take(&mut self.stats.events); + self.stat_criteria_changed(PLAYER_NAME, events); let board = &mut self.score.board; if !board.objectives.is_empty() { - for (ty, key, amount) in events { - let criteria = sb::stat_criteria(&ty, &key); - if board.has_objectives_for(&criteria) { - board.for_all_objectives(&criteria, PLAYER_NAME, |v| { - amount.map_or(0, |n| v.wrapping_add(n)) - }); - } - } let display = self.player_display_comp(); if let Some(p) = self.player.as_mut() { let health_and_absorption = p.health.health() + p.health.absorption(); diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index e66e68355..c36b99eaa 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -3,8 +3,12 @@ //! killed by, saved to `players/stats/.json`, plus the phantom //! spawner that reads the time since rest (`PhantomSpawner`). use super::{Dim, Game}; +use horizon_core::geometry::Vec3; use horizon_core::random::RandomSource; -use std::collections::BTreeMap; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, +}; /// `stats[type][key]`, with `type` and `key` namespaced ids. #[derive(Default)] @@ -16,6 +20,8 @@ pub(super) struct Stats { /// Statistic changes (type, key, amount; `None` = reset) for the /// scoreboard criteria to follow. pub(super) events: Vec<(String, String, Option)>, + /// Changed since the client was last sent them (`StatsCounter`'s dirty set). + pub(super) dirty: BTreeSet<(String, String)>, } impl Stats { pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) { @@ -28,6 +34,8 @@ impl Stats { *v = v.saturating_add(n); self.events .push((format!("minecraft:{ty}"), key.to_owned(), Some(n))); + self.dirty + .insert((format!("minecraft:{ty}"), key.to_owned())); } pub(super) fn get(&self, ty: &str, key: &str) -> i32 { self.values @@ -40,52 +48,51 @@ impl Stats { if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) { m.insert(key.to_owned(), 0); } + self.dirty + .insert((format!("minecraft:{ty}"), key.to_owned())); self.events .push((format!("minecraft:{ty}"), key.to_owned(), None)); } pub(super) fn custom(&mut self, key: &str, n: i32) { self.add("custom", &format!("minecraft:{key}"), n); } -} -impl Game<'_> { - fn stats_path(&self) -> Option { - let uuid = self.level.player_uuid?; - let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - let text = format!( - "{}-{}-{}-{}-{}", - &hex[0..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..32] - ); - Some( - self.world_root - .join("players/stats") - .join(format!("{text}.json")), - ) + /// `ServerStatsCounter.markAllDirty`: everything goes out on the next request. + pub(super) fn mark_all_dirty(&mut self) { + self.dirty = self + .values + .iter() + .flat_map(|(ty, m)| m.keys().map(|k| (ty.clone(), k.clone()))) + .collect(); } - /// `ServerStatsCounter.parseLocal`. - pub(super) fn load_stats(&mut self) { - if self.stats.loaded || self.remote.is_some() { - return; - } - self.stats.loaded = true; - let Some(path) = self.stats_path() else { - return; + /// `ServerStatsCounter.sendStats`' entries: the dirty statistics and + /// their values, the set cleared. + pub(super) fn take_dirty(&mut self) -> Vec<(String, String, i32)> { + std::mem::take(&mut self.dirty) + .into_iter() + .map(|(ty, key)| { + let v = self.values.get(&ty).and_then(|m| m.get(&key)).copied(); + (ty, key, v.unwrap_or(0)) + }) + .collect() + } + /// `ServerStatsCounter.parseLocal`: the counters of a stats file. + pub(super) fn read(path: &Path) -> Self { + let mut stats = Self { + loaded: true, + ..Self::default() }; - let Ok(text) = std::fs::read_to_string(path) else { - return; + let Some(json) = std::fs::read_to_string(path) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + else { + return stats; }; - let Ok(json) = serde_json::from_str::(&text) else { - return; - }; - if let Some(stats) = json.get("stats").and_then(|s| s.as_object()) { - for (ty, entries) in stats { + if let Some(all) = json.get("stats").and_then(|s| s.as_object()) { + for (ty, entries) in all { let Some(entries) = entries.as_object() else { continue; }; - let map = self.stats.values.entry(ty.clone()).or_default(); + let map = stats.values.entry(ty.clone()).or_default(); for (key, v) in entries { if let Some(n) = v.as_i64() { map.insert(key.clone(), n as i32); @@ -93,17 +100,11 @@ impl Game<'_> { } } } + stats } /// `ServerStatsCounter.save`. - pub(super) fn save_stats(&self) { - if !self.stats.loaded || self.remote.is_some() { - return; - } - let Some(path) = self.stats_path() else { - return; - }; + pub(super) fn write(&self, path: &Path) { let stats: serde_json::Map = self - .stats .values .iter() .filter(|(_, m)| !m.is_empty()) @@ -124,9 +125,55 @@ impl Game<'_> { let _ = std::fs::write(path, text); } } +} +/// `players//.json` of a world (advancements, stats). +pub(super) fn player_json(world: &Path, dir: &str, uuid: [i32; 4]) -> PathBuf { + let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect(); + let text = format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ); + world.join("players").join(dir).join(format!("{text}.json")) +} +impl Game<'_> { + fn stats_path(&self) -> Option { + Some(player_json( + &self.world_root, + "stats", + self.level.player_uuid?, + )) + } + /// `ServerStatsCounter.parseLocal`. + pub(super) fn load_stats(&mut self) { + if self.stats.loaded || self.remote.is_some() || self.no_player_here() { + return; + } + self.stats.loaded = true; + if let Some(path) = self.stats_path() { + self.stats.values = Stats::read(&path).values; + } + } + /// `ServerStatsCounter.save`. + pub(super) fn save_stats(&self) { + if !self.stats.loaded || self.remote.is_some() || self.no_player_here() { + return; + } + if let Some(path) = self.stats_path() { + self.stats.write(&path); + } + } /// The per-tick counters (`Player.tick`/`ServerPlayer.tick` awardStat). pub(super) fn tick_stats(&mut self) { self.load_stats(); + self.count_tick_stats(self.sleeping.is_some()); + self.tick_movement_stats(); + } + /// `Player.tick`'s counters for the player in `self.player`. + pub(super) fn count_tick_stats(&mut self, sleeping: bool) { let Some(p) = self.player.as_ref() else { return; }; @@ -137,21 +184,26 @@ impl Game<'_> { s.custom("total_world_time", 1); if alive { s.custom("time_since_death", 1); - if self.sleeping.is_none() { + if !sleeping { s.custom("time_since_rest", 1); } } if crouching { s.custom("sneak_time", 1); } - self.tick_movement_stats(); } - /// `Player.checkMovementStatistics` / `checkRidingStatistics`. fn tick_movement_stats(&mut self) { let Some(p) = self.player.as_ref() else { return; }; let d = p.position.subtract(self.previous_position); + self.movement_stats(d); + } + /// `Player.checkMovementStatistics` / `checkRidingStatistics` for one move. + pub(super) fn movement_stats(&mut self, d: Vec3) { + let Some(p) = self.player.as_ref() else { + return; + }; let horizontal = ((d.x * d.x + d.z * d.z).sqrt() * 100.0).round() as i32; let total = ((d.x * d.x + d.y * d.y + d.z * d.z).sqrt() * 100.0).round() as i32; // Teleports are not travel. diff --git a/crates/horizon-client/src/lan/advancements.rs b/crates/horizon-client/src/lan/advancements.rs index f3170d485..0e0caf7ff 100644 --- a/crates/horizon-client/src/lan/advancements.rs +++ b/crates/horizon-client/src/lan/advancements.rs @@ -4,11 +4,14 @@ //! ClientboundRecipeBookAddPacket) and the advancements the player may see go //! out in ClientboundUpdateAdvancementsPacket (PlayerAdvancements.flushDirty). use super::data::{SyncData, json_to_nbt}; -use crate::{advancements::Tree, recipe_book::RecipeIndex}; +use crate::{ + advancements::{Progress, Tree}, + recipe_book::{RecipeIndex, Settings}, +}; use horizon_protocol::buf::Writer; use serde_json::Value; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, BTreeSet, HashMap}, path::Path, }; @@ -54,8 +57,16 @@ impl ServerAdvancements { } } - /// The first tick of a player without advancements. - pub fn first_tick(&self, sync: &SyncData, now_millis: i64) -> FirstTick { + /// The first tick of a player without advancements: the criteria + /// `minecraft:tick` meets go into `progress` and the recipes their + /// advancements reward into `book`. + pub fn first_tick( + &self, + sync: &SyncData, + now_millis: i64, + progress: &mut Progress, + book: &mut Settings, + ) -> FirstTick { // CriteriaTriggers.TICK: the criteria it meets, and what they complete. let mut obtained: Vec> = vec![Vec::new(); self.tree.list.len()]; for (i, a) in self.tree.list.iter().enumerate() { @@ -77,25 +88,24 @@ impl ServerAdvancements { .all(|group| group.iter().any(|c| got.contains(&c.as_str()))) }) .collect(); + let date = crate::advancements::date_text(now_millis.div_euclid(1000)); + for (a, got) in self.tree.list.iter().zip(&obtained) { + for c in got { + progress.grant(&a.id, c, &date); + } + } // AdvancementRewards.grant: the recipes, in the advancements' order. let mut entries = Vec::new(); for (i, a) in self.tree.list.iter().enumerate() { if !done[i] { continue; } + book.add_recipes(&self.displays, &a.rewards.recipes); for id in &a.rewards.recipes { - entries.extend(self.book_entries(id, sync)); + entries.extend(self.book_entries(id, sync, NOTIFY_AND_HIGHLIGHT)); } } - let recipe_book_add = (!entries.is_empty()).then(|| { - let mut w = Writer::new(); - w.varint(entries.len() as i32); - for e in entries { - w.data.extend(e); - } - w.bool(false); // not a replacement - w.data - }); + let recipe_book_add = (!entries.is_empty()).then(|| book_add(entries, false)); // flushDirty: every advancement the player may see, and its progress. let visible = self.tree.visible(&self.kids, |i| done[i]); let shown: Vec = (0..self.tree.list.len()).filter(|i| visible[*i]).collect(); @@ -103,60 +113,14 @@ impl ServerAdvancements { w.bool(true); // the first packet resets the client's advancements w.varint(shown.len() as i32); for &i in &shown { - let a = &self.tree.list[i]; - w.string(&a.id); - w.bool(a.parent.is_some()); - if let Some(p) = &a.parent { - w.string(p); - } - w.bool(a.display.is_some()); - if let Some(d) = &a.display { - w.nbt(&json_to_nbt(&d.title)); - w.nbt(&json_to_nbt(&d.description)); - w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0)); - w.varint(1); - w.varint(0); - w.varint(0); - w.varint(match d.frame { - crate::advancements::Frame::Task => 0, - crate::advancements::Frame::Challenge => 1, - crate::advancements::Frame::Goal => 2, - }); - w.i32( - i32::from(d.background.is_some()) - | i32::from(d.show_toast) << 1 - | i32::from(d.hidden) << 2, - ); - if let Some(b) = &d.background { - w.string(b); - } - } - w.varint(a.requirements.len() as i32); - for group in &a.requirements { - w.varint(group.len() as i32); - for c in group { - w.string(c); - } - } - w.bool(false); // sends_telemetry_event - let (x, y) = self.layout[i].unwrap_or((0, 0.0)); - w.f32(x as f32); - w.f32(y); + self.write_advancement(&mut w, i, sync); } w.varint(0); // nothing removed w.varint(shown.len() as i32); for &i in &shown { - let a = &self.tree.list[i]; - w.string(&a.id); - w.varint(a.criteria.len() as i32); - for c in &a.criteria { - w.string(&c.name); - let got = obtained[i].contains(&c.name.as_str()); - w.bool(got); - if got { - w.i64(now_millis); - } - } + self.write_progress(&mut w, i, |c| { + obtained[i].contains(&c).then_some(now_millis) + }); } w.bool(true); // show the advancements FirstTick { @@ -165,9 +129,162 @@ impl ServerAdvancements { } } + /// `PlayerAdvancements.flushDirty`: the advancements that became visible + /// or hidden since `visible` (which it updates; empty before the first + /// packet, which resets the client's and carries everything visible) and + /// the progress of the `changed` ones still visible. None when there is + /// nothing to send. + pub fn update( + &self, + sync: &SyncData, + progress: &Progress, + visible: &mut Vec, + changed: &BTreeSet, + show: bool, + ) -> Option> { + let n = self.tree.list.len(); + let first = visible.len() != n; + let now = self + .tree + .visible(&self.kids, |i| progress.done(&self.tree.list[i])); + let was = |i: usize| !first && visible[i]; + let added: Vec = (0..n).filter(|&i| now[i] && !was(i)).collect(); + let removed: Vec = (0..n).filter(|&i| !now[i] && was(i)).collect(); + let progressed: Vec = if first { + (0..n).filter(|&i| now[i]).collect() + } else { + changed + .iter() + .copied() + .filter(|&i| i < n && now[i]) + .collect() + }; + *visible = now; + if !first && added.is_empty() && removed.is_empty() && progressed.is_empty() { + return None; + } + let mut w = Writer::new(); + w.bool(first); + w.varint(added.len() as i32); + for &i in &added { + self.write_advancement(&mut w, i, sync); + } + w.varint(removed.len() as i32); + for &i in &removed { + w.string(&self.tree.list[i].id); + } + w.varint(progressed.len() as i32); + for &i in &progressed { + let id = &self.tree.list[i].id; + self.write_progress(&mut w, i, |c| { + progress + .criteria + .get(id) + .and_then(|m| m.get(c)) + .map(|date| crate::advancements::date_millis(date).unwrap_or(0)) + }); + } + w.bool(show); + Some(w.data) + } + + /// Which advancements a player with `progress` may see. + pub fn visibility(&self, progress: &Progress) -> Vec { + self.tree + .visible(&self.kids, |i| progress.done(&self.tree.list[i])) + } + + /// `ClientboundUpdateAdvancementsPacket.PositionedAdvancement`. + fn write_advancement(&self, w: &mut Writer, i: usize, sync: &SyncData) { + let a = &self.tree.list[i]; + w.string(&a.id); + w.bool(a.parent.is_some()); + if let Some(p) = &a.parent { + w.string(p); + } + w.bool(a.display.is_some()); + if let Some(d) = &a.display { + w.nbt(&json_to_nbt(&d.title)); + w.nbt(&json_to_nbt(&d.description)); + w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0)); + w.varint(1); + w.varint(0); + w.varint(0); + w.varint(match d.frame { + crate::advancements::Frame::Task => 0, + crate::advancements::Frame::Challenge => 1, + crate::advancements::Frame::Goal => 2, + }); + w.i32( + i32::from(d.background.is_some()) + | i32::from(d.show_toast) << 1 + | i32::from(d.hidden) << 2, + ); + if let Some(b) = &d.background { + w.string(b); + } + } + w.varint(a.requirements.len() as i32); + for group in &a.requirements { + w.varint(group.len() as i32); + for c in group { + w.string(c); + } + } + w.bool(false); // sends_telemetry_event + let (x, y) = self.layout[i].unwrap_or((0, 0.0)); + w.f32(x as f32); + w.f32(y); + } + + /// An `AdvancementProgress`: each criterion and when it was obtained. + fn write_progress(&self, w: &mut Writer, i: usize, obtained: impl Fn(&str) -> Option) { + let a = &self.tree.list[i]; + w.string(&a.id); + w.varint(a.criteria.len() as i32); + for c in &a.criteria { + w.string(&c.name); + let at = obtained(&c.name); + w.bool(at.is_some()); + if let Some(at) = at { + w.i64(at); + } + } + } + + /// `ServerRecipeBook.addRecipes`' packet for recipes just unlocked: + /// each display, with its notification and highlighted. None when no + /// recipe has a display. + pub fn recipes_added(&self, ids: &[String], sync: &SyncData) -> Option> { + let entries: Vec> = ids + .iter() + .flat_map(|id| self.book_entries(id, sync, NOTIFY_AND_HIGHLIGHT)) + .collect(); + (!entries.is_empty()).then(|| book_add(entries, false)) + } + + /// `ServerRecipeBook.sendInitialRecipeBook`: every known recipe, without + /// notifications, highlighted while not yet displayed, replacing the + /// client's book. + pub fn initial_recipe_book(&self, book: &Settings, sync: &SyncData) -> Vec { + let entries: Vec> = book + .recipes + .iter() + .flat_map(|id| { + let highlight = if book.to_be_displayed.contains(id) { + 2 + } else { + 0 + }; + self.book_entries(id, sync, highlight) + }) + .collect(); + book_add(entries, true) + } + /// ClientboundRecipeBookAddPacket.Entry for each display of a recipe: /// highlighted, and with a notification unless the recipe turns it off. - fn book_entries(&self, id: &str, sync: &SyncData) -> Vec> { + fn book_entries(&self, id: &str, sync: &SyncData, flags: i8) -> Vec> { let Some(r) = self.recipes.get(id) else { return Vec::new(); }; @@ -245,12 +362,27 @@ impl ServerAdvancements { for v in placed { holder_set(&mut w, v, &item); } + // The notification only where the recipe shows one. let notify = r["show_notification"].as_bool().unwrap_or(true); - w.i8(i8::from(notify) | 2); + w.i8(if notify { flags } else { flags & !1 }); vec![w.data] } } +/// ClientboundRecipeBookAddPacket.Entry flags: notification, highlight. +const NOTIFY_AND_HIGHLIGHT: i8 = 1 | 2; + +/// ClientboundRecipeBookAddPacket: the entries, then whether they replace the book. +fn book_add(entries: Vec>, replace: bool) -> Vec { + let mut w = Writer::new(); + w.varint(entries.len() as i32); + for e in entries { + w.data.extend(e); + } + w.bool(replace); + w.data +} + /// ShapedRecipePattern.shrink: the pattern without blank border rows and columns. fn shrink(rows: &[Value]) -> Vec> { let rows: Vec> = rows diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 108e0c2c7..e540a9e8f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -136,6 +136,19 @@ pub struct Guest { pub drag: Option<(u8, Vec)>, /// The compound this player was loaded from, for fields Horizon does not model. pub saved: Option, + /// `ServerPlayer.recipeBook`. + pub recipe_book: crate::recipe_book::Settings, + /// `PlayerAdvancements`: the criteria obtained, whether they came from + /// the player's file, the advancements the client was last told it may + /// see (empty before the first packet), and those whose progress + /// changed since (`progressChanged`). + pub advancements: crate::advancements::Progress, + pub advancements_loaded: bool, + pub advancements_visible: Vec, + pub advancements_changed: std::collections::BTreeSet, + /// Recipes unlocked since the client was last told + /// (`ServerRecipeBook.addRecipes` sends them). + pub recipes_unlocked: Vec, } impl Guest { @@ -214,6 +227,12 @@ impl Guest { next_window: 0, drag: None, saved: None, + recipe_book: Default::default(), + advancements: Default::default(), + advancements_loaded: false, + advancements_visible: Vec::new(), + advancements_changed: Default::default(), + recipes_unlocked: Vec::new(), } } pub fn send(&self, packet: &play::Clientbound) { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index fad9e0e7d..806c91fc3 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -509,12 +509,18 @@ impl Hub { g.send(&raw(ids::UPDATE_RECIPES, self.sync.recipes.clone())); // PlayerList.sendPlayerPermissionLevel, then the recipe book. self.send_permission_level(i); + // ServerRecipeBook.sendInitialRecipeBook: each book's open and + // filtering flags, then every known recipe. let g = &self.guests[i]; + let book = &g.recipe_book; + let settings = (0..4) + .flat_map(|b| [u8::from(book.open[b]), u8::from(book.filtering[b])]) + .collect(); + g.send(&raw(ids::RECIPE_BOOK_SETTINGS, settings)); g.send(&raw( - ids::RECIPE_BOOK_SETTINGS, - vec![0; 8], // four books, each closed and unfiltered + ids::RECIPE_BOOK_ADD, + self.sync.advancements.initial_recipe_book(book, &self.sync), )); - g.send(&raw(ids::RECIPE_BOOK_ADD, vec![0, 1])); // no entries, replace // The others hear of the newcomer before it joins the list. self.broadcast_except( conn, @@ -1408,15 +1414,29 @@ impl Hub { id: g.entity_id, values: vec![(9, serializer::FLOAT, Value::Float(g.health))], })); - // ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty. - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as i64); - let first = self.sync.advancements.first_tick(&self.sync, now); - if let Some(add) = first.recipe_book_add { - g.send(&raw(ids::RECIPE_BOOK_ADD, add)); + // ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty. A + // player who has been here has had the tick's criteria already. + if !g.advancements_loaded { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64); + let sync = self.sync.clone(); + let g = &mut self.guests[i]; + let first = sync.advancements.first_tick( + &sync, + now, + &mut g.advancements, + &mut g.recipe_book, + ); + if let Some(add) = first.recipe_book_add { + g.send(&raw(ids::RECIPE_BOOK_ADD, add)); + } + g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements)); + g.advancements_visible = sync.advancements.visibility(&g.advancements); + g.advancements_changed.clear(); + } else { + self.flush_advancements(i, true); } - g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements)); } let health = { let g = &self.guests[i]; @@ -1467,6 +1487,65 @@ impl Hub { } } + /// `PlayerAdvancements.flushDirty` and the recipes the player unlocked + /// since (`ServerRecipeBook.addRecipes`), once the player's first tick + /// has sent their advancements. + pub fn flush_progress(&mut self, conn: u32) { + if let Some(i) = self.guests.iter().position(|g| g.conn == conn) + && self.guests[i].sent_health.is_some() + { + self.flush_advancements(i, true); + } + } + fn flush_advancements(&mut self, i: usize, show: bool) { + let sync = self.sync.clone(); + let g = &mut self.guests[i]; + let unlocked = std::mem::take(&mut g.recipes_unlocked); + if let Some(add) = sync.advancements.recipes_added(&unlocked, &sync) { + g.send(&raw(ids::RECIPE_BOOK_ADD, add)); + } + let changed = std::mem::take(&mut g.advancements_changed); + if let Some(update) = sync.advancements.update( + &sync, + &g.advancements, + &mut g.advancements_visible, + &changed, + show, + ) { + g.send(&raw(ids::UPDATE_ADVANCEMENTS, update)); + } + } + + /// ClientboundAwardStatsPacket (`ServerStatsCounter.sendStats`): each + /// statistic as its type and value by network id (`Stat.STREAM_CODEC`), + /// then its count. Statistics the registries don't know are left out. + pub fn send_stats(&self, conn: u32, stats: &[(String, String, i32)]) { + let known: Vec<(i32, i32, i32)> = stats + .iter() + .filter_map(|(ty, key, count)| { + let values = match ty.as_str() { + "minecraft:mined" => "minecraft:block", + "minecraft:killed" | "minecraft:killed_by" => "minecraft:entity_type", + "minecraft:custom" => "minecraft:custom_stat", + _ => "minecraft:item", + }; + Some(( + self.sync.id("minecraft:stat_type", ty)?, + self.sync.id(values, key)?, + *count, + )) + }) + .collect(); + let mut w = horizon_protocol::buf::Writer::new(); + w.varint(known.len() as i32); + for (ty, value, count) in known { + w.varint(ty); + w.varint(value); + w.varint(count); + } + self.send_to(conn, &raw(ids::AWARD_STATS, w.data)); + } + // ---- incoming ------------------------------------------------------ /// The squared movement past 1.0E-5F (handlePlayerKnownMovement). diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index d824683d2..555463685 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -70,6 +70,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.game_mode = level.mode(); guest.selected = (level.selected_slot.max(0) as usize).min(8); guest.saved = level.player_extra.clone(); + guest.recipe_book = level.recipe_book.clone(); if level.ender_items.len() == 27 { guest.ender_items = level.ender_items.clone(); } @@ -126,6 +127,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.selected_slot = guest.selected as i32; level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); + level.recipe_book = guest.recipe_book.clone(); level.ender_items = guest.ender_items.clone(); level.inventory.clear(); level.inventory_components.clear(); From ee104603dde8ebbe5c86efa939de4259f958fd16 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 06:06:02 +0200 Subject: [PATCH 023/327] horizon-port-pack: a library, fetch and port; CurseForge zips name their mods The launcher's "Import modpack" needs the pipeline as a library and a way to get the jars a pack names without redistributing anything. - The steps move into the library (pipeline.rs) with a line callback, so the command line and the launcher run the same code; main.rs is a thin CLI. - fetch: the jars of the portable mods (content, data tier) into /jars/, the player's own downloads: copied from a folder they have (by SHA-1, or a CurseForge app instance's minecraftinstance.json), else from the pack's own link (.mrpack hosts only) or the same file on Modrinth's public CDN found by SHA-1, kept only when the hash matches. What only CurseForge has is listed as needing a CurseForge API key. /fetch.json records each file. - port: every step after the import for the portable mods (fetch, the inventory again with the jars read, carry, report). - A CurseForge zip whose overrides hold Crash Assistant's modlist.json (All the Mods 10 does) takes its jar names, mod ids and SHA-1s instead of bare project ids, so Modrinth answers for most files. - inventory goes on offline when Modrinth cannot be reached. All the Mods 10 8.3's CurseForge zip: 496 files named; of the 54 data-tier content mods 42 download from Modrinth's CDN (84 MB) and 12 need the key or the player's instance; 42 carried over (partial: the harness is a dev step). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-port-pack/src/fetch.rs | 389 +++++++++++++++++++++++ crates/horizon-port-pack/src/import.rs | 59 +++- crates/horizon-port-pack/src/lib.rs | 17 + crates/horizon-port-pack/src/main.rs | 259 +++++---------- crates/horizon-port-pack/src/modrinth.rs | 6 +- crates/horizon-port-pack/src/pipeline.rs | 237 ++++++++++++++ crates/horizon-port-pack/src/report.rs | 2 +- docs/modpacks.md | 20 +- 8 files changed, 793 insertions(+), 196 deletions(-) create mode 100644 crates/horizon-port-pack/src/fetch.rs create mode 100644 crates/horizon-port-pack/src/lib.rs create mode 100644 crates/horizon-port-pack/src/pipeline.rs diff --git a/crates/horizon-port-pack/src/fetch.rs b/crates/horizon-port-pack/src/fetch.rs new file mode 100644 index 000000000..011e99e1f --- /dev/null +++ b/crates/horizon-port-pack/src/fetch.rs @@ -0,0 +1,389 @@ +//! Step 1b, the jars: for the mods the player asked to port, their own +//! download of each jar into `/jars/`. Only from where the pack itself +//! points (a Modrinth pack's download URLs) or the same file on Modrinth's +//! public CDN (found by its SHA-1), and only kept when the hash matches; or +//! copied from a folder the player already has (an installed instance, a +//! downloads folder). CurseForge's own downloads need an API key, so a file +//! only CurseForge has is listed as needing one. `/fetch.json` says +//! what happened to each file. +use crate::{ + import::{Pack, PackFile, sha1_hex}, + inventory::Record, + modrinth::{self, Cache}, + pipeline::{Log, read_json, write_json}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{ + collections::HashMap, + fs, + io::Read, + path::{Path, PathBuf}, +}; + +/// Hosts a Modrinth pack may download from (the `.mrpack` format's list). +const HOSTS: [&str; 4] = [ + "https://cdn.modrinth.com/", + "https://github.com/", + "https://raw.githubusercontent.com/", + "https://gitlab.com/", +]; +/// No mod jar is this large; a bigger answer is not one. +const MAX_JAR: u64 = 512 << 20; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum How { + /// Already in `jars/` (or the imported instance). + Present, + /// Downloaded from the pack's URL or Modrinth's CDN, hash checked. + Downloaded, + /// Copied from the player's folder. + Local, + /// Only on CurseForge, whose downloads need an API key. + NeedsKey, + NotFound, + Failed, +} + +impl How { + pub fn label(self) -> &'static str { + match self { + How::Present => "already here", + How::Downloaded => "downloaded", + How::Local => "copied from your folder", + How::NeedsKey => "needs a CurseForge key", + How::NotFound => "not found", + How::Failed => "failed", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Outcome { + pub key: String, + pub file: String, + pub how: How, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub detail: String, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Fetched { + pub files: Vec, +} + +impl Fetched { + pub fn count(&self, how: How) -> usize { + self.files.iter().filter(|o| o.how == how).count() + } + /// `/fetch.json`, empty when the step has not run. + pub fn load(work: &Path) -> Self { + read_json(&work.join("fetch.json")).unwrap_or_default() + } +} + +/// The jars of the records `want` picks that the work folder lacks. +pub fn fetch( + work: &Path, + records: &[Record], + from: Option<&Path>, + want: &dyn Fn(&Record) -> bool, + log: Log, +) -> Result { + let pack: Pack = read_json(&work.join("pack.json"))?; + let cache = Cache::load(&work.join("modrinth.json")); + let files: HashMap<&str, &PackFile> = pack.files.iter().map(|f| (f.path.as_str(), f)).collect(); + let jars = work.join("jars"); + fs::create_dir_all(&jars).map_err(|e| format!("{}: {e}", jars.display()))?; + let local = from.map(Local::index); + let wanted: Vec<&Record> = records.iter().filter(|r| want(r)).collect(); + let mut fetched = Fetched::default(); + for (i, r) in wanted.iter().enumerate() { + let Some(file) = files.get(r.path.as_str()) else { + continue; + }; + let name = file.file_name(); + let outcome = |how, detail: String| Outcome { + key: r.key.clone(), + file: name.to_owned(), + how, + detail, + }; + let dest = jars.join(name); + let sha1 = file.sha1.as_deref(); + let o = if r.jar.is_some() || matches(&dest, sha1) { + outcome(How::Present, String::new()) + } else if let Some(path) = local.as_ref().and_then(|l| l.find(file)) { + match fs::copy(&path, &dest) { + Ok(_) => outcome(How::Local, path.display().to_string()), + Err(e) => outcome(How::Failed, format!("{}: {e}", path.display())), + } + } else if let Some(url) = url_of(file, &cache) { + log(format!("{}/{} {name}", i + 1, wanted.len())); + match download(&url, sha1, &dest) { + Ok(()) => outcome(How::Downloaded, url), + Err(e) => outcome(How::Failed, e), + } + } else if pack.format == "curseforge" || file.curseforge.is_some() { + outcome( + How::NeedsKey, + "on CurseForge only: choose your installed instance, or put the jar in jars/" + .into(), + ) + } else { + outcome(How::NotFound, "no download link in the pack".into()) + }; + if matches!(o.how, How::Failed | How::NeedsKey | How::NotFound) { + log(format!("{}: {} ({})", o.key, o.how.label(), o.detail)); + } + fetched.files.push(o); + } + write_json(&work.join("fetch.json"), &fetched)?; + log(format!( + "jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed", + fetched.count(How::Downloaded), + fetched.count(How::Local), + fetched.count(How::Present), + fetched.count(How::NeedsKey), + fetched.count(How::NotFound), + fetched.count(How::Failed) + )); + Ok(fetched) +} + +/// Whether `path` holds the file with this SHA-1 (any file when none is known). +fn matches(path: &Path, sha1: Option<&str>) -> bool { + match (fs::read(path), sha1) { + (Ok(bytes), Some(h)) => sha1_hex(&bytes).eq_ignore_ascii_case(h), + (Ok(_), None) => true, + (Err(_), _) => false, + } +} + +/// The pack's own download link, else the same file on Modrinth. +pub fn url_of(file: &PackFile, cache: &Cache) -> Option { + let allowed = |u: &&str| HOSTS.iter().any(|h| u.starts_with(h)); + if let Some(u) = file.downloads.iter().map(String::as_str).find(allowed) { + return Some(u.to_owned()); + } + let sha1 = file.sha1.as_deref()?; + cache.versions.get(sha1)?["files"] + .as_array()? + .iter() + .find(|f| f["hashes"]["sha1"].as_str() == Some(sha1))?["url"] + .as_str() + .filter(allowed) + .map(str::to_owned) +} + +/// Downloads `url` to `dest`, kept only if its SHA-1 is `sha1`. +fn download(url: &str, sha1: Option<&str>, dest: &Path) -> Result<(), String> { + let response = ureq::get(url) + .set("User-Agent", modrinth::AGENT) + .call() + .map_err(|e| format!("{url}: {e}"))?; + let mut bytes = Vec::new(); + response + .into_reader() + .take(MAX_JAR) + .read_to_end(&mut bytes) + .map_err(|e| format!("{url}: {e}"))?; + let got = sha1_hex(&bytes); + if let Some(want) = sha1.filter(|w| !w.eq_ignore_ascii_case(&got)) { + return Err(format!("{url}: SHA-1 {got}, the pack says {want}")); + } + let part = dest.with_extension("part"); + fs::write(&part, &bytes).map_err(|e| format!("{}: {e}", part.display()))?; + fs::rename(&part, dest).map_err(|e| format!("{}: {e}", dest.display())) +} + +/// The jars in a folder of the player's, by SHA-1 and by name, and what a +/// CurseForge app instance (`minecraftinstance.json`) says each +/// project's file is called. +#[derive(Default)] +struct Local { + by_sha1: HashMap, + by_name: HashMap, + curseforge: HashMap<(u64, u64), String>, +} + +impl Local { + fn index(dir: &Path) -> Local { + let mut local = Local::default(); + local.walk(dir, 3); + if let Ok(text) = fs::read_to_string(dir.join("minecraftinstance.json")) { + if let Ok(v) = serde_json::from_str::(&text) { + local.curseforge = curseforge_names(&v); + } + } + local + } + + fn walk(&mut self, dir: &Path, depth: usize) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for path in entries.flatten().map(|e| e.path()) { + if path.is_dir() { + if depth > 0 { + self.walk(&path, depth - 1); + } + } else if path.extension().is_some_and(|x| x == "jar") { + if let Ok(bytes) = fs::read(&path) { + self.by_sha1.insert(sha1_hex(&bytes), path.clone()); + } + if let Some(n) = path.file_name() { + self.by_name + .insert(n.to_string_lossy().into_owned(), path.clone()); + } + } + } + } + + fn find(&self, file: &PackFile) -> Option { + if let Some(h) = &file.sha1 { + return self.by_sha1.get(&h.to_ascii_lowercase()).cloned(); + } + let name = file + .curseforge + .and_then(|ids| self.curseforge.get(&ids)) + .map_or(file.file_name(), String::as_str); + self.by_name.get(name).cloned() + } +} + +/// `installedAddons[]`: (project, file) → the jar's file name. +pub fn curseforge_names(instance: &Value) -> HashMap<(u64, u64), String> { + instance["installedAddons"] + .as_array() + .into_iter() + .flatten() + .filter_map(|a| { + let file = &a["installedFile"]; + Some(( + (a["addonID"].as_u64()?, file["id"].as_u64()?), + file["fileName"].as_str()?.to_owned(), + )) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn file(sha1: Option<&str>, downloads: &[&str]) -> PackFile { + PackFile { + path: "mods/a.jar".into(), + sha1: sha1.map(str::to_owned), + downloads: downloads.iter().map(|d| (*d).to_owned()).collect(), + ..PackFile::default() + } + } + + #[test] + fn links_come_from_the_pack_or_modrinth_and_only_allowed_hosts() { + let mut cache = Cache::default(); + cache.versions.insert( + "ab".into(), + json!({"files": [ + {"hashes": {"sha1": "cd"}, "url": "https://cdn.modrinth.com/other.jar"}, + {"hashes": {"sha1": "ab"}, "url": "https://cdn.modrinth.com/a.jar"}]}), + ); + let pack_link = file( + Some("ab"), + &["https://evil.example/a.jar", "https://github.com/a.jar"], + ); + assert_eq!( + url_of(&pack_link, &cache).as_deref(), + Some("https://github.com/a.jar") + ); + let modrinth = file(Some("ab"), &["https://evil.example/a.jar"]); + assert_eq!( + url_of(&modrinth, &cache).as_deref(), + Some("https://cdn.modrinth.com/a.jar") + ); + assert_eq!(url_of(&file(Some("ef"), &[]), &cache), None); + assert_eq!(url_of(&file(None, &[]), &cache), None); + } + + #[test] + fn reads_a_curseforge_instance() { + let instance = json!({"installedAddons": [ + {"addonID": 238222, "installedFile": {"id": 5101366, "fileName": "jei-1.21.1.jar"}}, + {"addonID": 1, "installedFile": {"fileName": "no-id.jar"}}]}); + let names = curseforge_names(&instance); + assert_eq!(names.len(), 1); + assert_eq!(names[&(238222, 5101366)], "jei-1.21.1.jar"); + } + + #[test] + fn copies_the_players_jars_and_lists_what_needs_a_key() { + let root = std::env::temp_dir().join(format!("horizon-fetch-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let (work, mine) = (root.join("work"), root.join("instance/mods")); + fs::create_dir_all(&mine).unwrap(); + fs::create_dir_all(&work).unwrap(); + fs::write(mine.join("renamed.jar"), b"jar a").unwrap(); + fs::write(mine.join("cf.jar"), b"jar b").unwrap(); + fs::write( + root.join("instance/minecraftinstance.json"), + json!({"installedAddons": [{"addonID": 7, "installedFile": {"id": 8, "fileName": "cf.jar"}}]}) + .to_string(), + ) + .unwrap(); + let pack = Pack { + format: "curseforge".into(), + files: vec![ + PackFile { + path: "mods/a.jar".into(), + sha1: Some(sha1_hex(b"jar a")), + ..PackFile::default() + }, + PackFile { + path: "mods/curseforge-7-8".into(), + curseforge: Some((7, 8)), + ..PackFile::default() + }, + PackFile { + path: "mods/curseforge-9-9".into(), + curseforge: Some((9, 9)), + ..PackFile::default() + }, + ], + ..Pack::default() + }; + write_json(&work.join("pack.json"), &pack).unwrap(); + let records: Vec = pack + .files + .iter() + .map(|f| Record { + key: f.file_name().into(), + path: f.path.clone(), + ..Record::default() + }) + .collect(); + let fetched = fetch( + &work, + &records, + Some(&root.join("instance")), + &|_| true, + &|_| {}, + ) + .unwrap(); + let hows: Vec = fetched.files.iter().map(|o| o.how).collect(); + assert_eq!(hows, [How::Local, How::Local, How::NeedsKey]); + assert_eq!(fs::read(work.join("jars/a.jar")).unwrap(), b"jar a"); + assert_eq!( + fs::read(work.join("jars/curseforge-7-8")).unwrap(), + b"jar b" + ); + // A second run finds them in place. + let again = fetch(&work, &records, None, &|_| true, &|_| {}).unwrap(); + assert_eq!(again.count(How::Present), 2); + assert_eq!(Fetched::load(&work).count(How::Present), 2); + fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/crates/horizon-port-pack/src/import.rs b/crates/horizon-port-pack/src/import.rs index dd712acf1..0a3aa8d06 100644 --- a/crates/horizon-port-pack/src/import.rs +++ b/crates/horizon-port-pack/src/import.rs @@ -22,8 +22,20 @@ pub struct Pack { pub files: Vec, /// Override files by top folder (`config`, `kubejs`, ...). pub overrides: BTreeMap, + /// A CurseForge zip's files by project and file id only: how many its + /// manifest lists, when the files came from the pack's own mod list. + #[serde(default, skip_serializing_if = "is_zero")] + pub curseforge_files: usize, } +fn is_zero(n: &usize) -> bool { + *n == 0 +} + +/// Where Crash Assistant keeps its list in an instance (and in the +/// overrides of packs that ship it, such as All the Mods 10). +pub const MODLIST: &str = "config/crash_assistant/modlist.json"; + #[derive(Debug, Default, Serialize, Deserialize)] pub struct PackFile { /// Path in the instance (`mods/create-1.21.1-6.0.4.jar`). @@ -83,7 +95,16 @@ pub fn import(path: &Path) -> Result { return Ok(mrpack(&index, &names(&zip))); } if let Some(manifest) = read_json(&mut zip, "manifest.json")? { - return Ok(curseforge(&manifest, &names(&zip))); + let mut pack = curseforge(&manifest, &names(&zip)); + // The manifest names files only by CurseForge ids, which need a key + // to resolve; the pack's own mod list names them and gives their + // SHA-1s, so Modrinth can answer for most. + let root = manifest["overrides"].as_str().unwrap_or("overrides"); + if let Some(list) = read_json(&mut zip, &format!("{root}/{MODLIST}"))? { + pack.curseforge_files = pack.files.len(); + pack.files = modlist(&list)?.files; + } + return Ok(pack); } Err(format!( "{}: neither modrinth.index.json nor manifest.json", @@ -103,7 +124,7 @@ fn read_json(zip: &mut zip::ZipArchive, name: &str) -> Result Pack { names, &["overrides", "client-overrides", "server-overrides"], ), + ..Pack::default() } } @@ -197,6 +219,7 @@ pub fn curseforge(manifest: &Value, names: &[String]) -> Pack { loader_version: loader_version.to_owned(), files, overrides: overrides(names, &[root]), + ..Pack::default() } } @@ -418,4 +441,36 @@ mod tests { assert_eq!(p.files[0].curseforge, Some((238222, 5101366))); assert_eq!(p.overrides["kubejs"], 1); } + + #[test] + fn a_curseforge_zip_takes_names_from_its_mod_list() { + use std::io::Write; + let dir = std::env::temp_dir().join(format!("horizon-cf-zip-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let path = dir.join("pack.zip"); + let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let opts = zip::write::SimpleFileOptions::default(); + let manifest = json!({"name": "Pack", "overrides": "overrides", + "minecraft": {"version": "1.21.1", "modLoaders": [{"id": "neoforge-21.1.259"}]}, + "files": [{"projectID": 1, "fileID": 2}, {"projectID": 3, "fileID": 4}]}); + zip.start_file("manifest.json", opts).unwrap(); + zip.write_all(manifest.to_string().as_bytes()).unwrap(); + zip.start_file(format!("overrides/{MODLIST}"), opts) + .unwrap(); + let list = json!({"mcw-doors-1.1.2.jar": {"jarName": "mcw-doors-1.1.2.jar", + "modId": "mcwdoors", "modrinthHash": "0123456789abcdef0123456789abcdef01234567"}}); + // Crash Assistant writes a byte order mark. + zip.write_all(format!("\u{feff}{list}").as_bytes()).unwrap(); + zip.finish().unwrap(); + let pack = import(&path).unwrap(); + assert_eq!( + (pack.format.as_str(), pack.name.as_str()), + ("curseforge", "Pack") + ); + assert_eq!(pack.curseforge_files, 2); + assert_eq!(pack.files.len(), 1); + assert_eq!(pack.files[0].path, "mods/mcw-doors-1.1.2.jar"); + assert_eq!(pack.overrides["config"], 1); + fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs new file mode 100644 index 000000000..ecd61956c --- /dev/null +++ b/crates/horizon-port-pack/src/lib.rs @@ -0,0 +1,17 @@ +//! Port a Java modpack to Horizon (`docs/modpacks.md`): the steps behind the +//! `horizon-port-pack` command, and the launcher's "Import modpack". +//! +//! Every step reads and writes files in a work folder (`pipeline`), so it can +//! be rerun, resumed and inspected. The work folder belongs to the user: the +//! jars they downloaded and what is carried over from them stay there and +//! are never uploaded or committed. +pub mod carry; +pub mod classify; +pub mod fetch; +pub mod import; +pub mod inventory; +pub mod jar; +pub mod modrinth; +pub mod oracle; +pub mod pipeline; +pub mod report; diff --git a/crates/horizon-port-pack/src/main.rs b/crates/horizon-port-pack/src/main.rs index 3e6cdf4d7..e766a442d 100644 --- a/crates/horizon-port-pack/src/main.rs +++ b/crates/horizon-port-pack/src/main.rs @@ -6,57 +6,77 @@ //! `/modrinth.json`), the jars in the instance or `/jars/`, //! classes, tiers and dependency layers in `/inventory.json` and //! `inventory.csv`. +//! - `fetch [--from ] [...]`: the jars of the +//! portable mods (content, data tier; or the ones named) into +//! `/jars/`: copied from the player's folder, or downloaded from the +//! pack's own links or Modrinth's CDN, hash checked. What only CurseForge +//! has needs a key and is listed in `/fetch.json`. //! - `carry [--resources ] [...]`: the content //! mods' data and assets into `/mods//carry/`, a folder mod for //! local use. With the NeoForge oracle's `/oracle/facts.json` //! (`tools/neoforge_oracle.py`), blocks and items come from its facts; //! `--resources` limits templates to the blocks Horizon's tables have. -//! //! - `report `: the coverage report, per mod ported, partial, not yet //! or not needed with the reason, in `/coverage.json` and //! `coverage.md`. +//! - `port [--from ] [--resources ]`: every +//! step for the portable mods, as the launcher's "Import modpack" runs it. //! //! The work folder belongs to the user: jars and carried-over files stay //! there and are never uploaded or committed. -mod carry; -mod classify; -mod import; -mod inventory; -mod jar; -mod modrinth; -mod oracle; -mod report; +use horizon_port_pack::{fetch, inventory::Record, pipeline}; +use std::{ + path::{Path, PathBuf}, + process::ExitCode, +}; -use std::{fs, path::Path, process::ExitCode}; - -const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | carry [--resources ] [...] | report "; +const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | fetch [--from ] [...] | carry [--resources ] [...] | report | port [--from ] [--resources ]"; fn main() -> ExitCode { - let args: Vec = std::env::args().skip(1).collect(); - let path = |i: usize| args.get(i).map(Path::new).ok_or(USAGE.to_owned()); - let result = match args.first().map(String::as_str) { - Some("import") => path(1) - .and_then(|p| Ok((p, path(2)?))) - .and_then(|(p, w)| import(p, w)), - Some("inventory") => { - path(1).and_then(|w| inventory(w, args.iter().any(|a| a == "--offline"))) + let mut args: Vec = std::env::args().skip(1).collect(); + let result = (|| { + let from = option(&mut args, "--from")?; + let resources = option(&mut args, "--resources")?; + let offline = take_flag(&mut args, "--offline"); + let path = |i: usize| args.get(i).map(Path::new).ok_or(USAGE.to_owned()); + let rest = || args.get(2..).unwrap_or_default().to_vec(); + let log = &|line: String| println!("{line}"); + match args.first().map(String::as_str) { + Some("import") => pipeline::import(path(1)?, path(2)?, log).map(drop), + Some("inventory") => pipeline::inventory(path(1)?, offline, log).map(drop), + Some("fetch") => { + let work = path(1)?; + let records: Vec = pipeline::read_json(&work.join("inventory.json"))?; + let only = rest(); + let want = |r: &Record| { + if only.is_empty() { + pipeline::portable(r) + } else { + only.contains(&r.key) + } + }; + fetch::fetch(work, &records, from.as_deref(), &want, log).map(drop) + } + Some("carry") => { + pipeline::carry(path(1)?, resources.as_deref(), &rest(), log).map(drop) + } + Some("report") => { + let work = path(1)?; + pipeline::report(work, log)?; + println!("{}", work.join("coverage.md").display()); + Ok(()) + } + Some("port") => { + let work = path(2)?; + pipeline::import(path(1)?, work, log)?; + pipeline::inventory(work, offline, log)?; + pipeline::port(work, resources.as_deref(), from.as_deref(), log)?; + println!("{}", work.join("coverage.md").display()); + Ok(()) + } + _ => Err(USAGE.to_owned()), } - Some("carry") => path(1).and_then(|w| { - let mut rest = args[2..].to_vec(); - let resources = match rest.iter().position(|a| a == "--resources") { - Some(i) if i + 1 < rest.len() => { - let r = rest.remove(i + 1); - rest.remove(i); - Some(std::path::PathBuf::from(r)) - } - Some(_) => return Err(USAGE.to_owned()), - None => None, - }; - carry(w, resources.as_deref(), &rest) - }), - Some("report") => path(1).and_then(report), - _ => Err(USAGE.to_owned()), - }; + })(); match result { Ok(()) => ExitCode::SUCCESS, Err(e) => { @@ -66,158 +86,21 @@ fn main() -> ExitCode { } } -fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<(), String> { - let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; - fs::write(path, text).map_err(|e| format!("{}: {e}", path.display())) -} - -fn read_json(path: &Path) -> Result { - let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; - serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) -} - -fn report(work: &Path) -> Result<(), String> { - let pack: import::Pack = read_json(&work.join("pack.json"))?; - let records: Vec = read_json(&work.join("inventory.json"))?; - let rows = report::build(&records, work); - write_json(&work.join("coverage.json"), &rows)?; - let title = format!( - "{} ({} {}, Minecraft {})", - pack.name, pack.loader, pack.loader_version, pack.minecraft - ); - fs::write(work.join("coverage.md"), report::markdown(&title, &rows)) - .map_err(|e| format!("coverage.md: {e}"))?; - println!("{title}: {} files: {:?}", rows.len(), report::counts(&rows)); - println!("{}", work.join("coverage.md").display()); - Ok(()) -} - -fn import(pack: &Path, work: &Path) -> Result<(), String> { - let pack = import::import(pack)?; - fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?; - write_json(&work.join("pack.json"), &pack)?; - let mut kinds = std::collections::BTreeMap::<&str, usize>::new(); - for f in &pack.files { - *kinds.entry(f.kind()).or_default() += 1; - } - println!( - "{} ({}): Minecraft {}, {} {}; files {kinds:?}; overrides {:?}", - pack.name, pack.format, pack.minecraft, pack.loader, pack.loader_version, pack.overrides - ); - Ok(()) -} - -fn inventory(work: &Path, offline: bool) -> Result<(), String> { - let pack: import::Pack = read_json(&work.join("pack.json"))?; - let cache_path = work.join("modrinth.json"); - let mut cache = modrinth::Cache::load(&cache_path); - if !offline { - let hashes: Vec = pack.files.iter().filter_map(|f| f.sha1.clone()).collect(); - cache.fetch(&hashes)?; - write_json(&cache_path, &cache)?; - } - let records = inventory::build(&pack, &cache, work); - write_json(&work.join("inventory.json"), &records)?; - fs::write(work.join("inventory.csv"), inventory::csv(&records)) - .map_err(|e| format!("inventory.csv: {e}"))?; - let jars = records.iter().filter(|r| r.jar.is_some()).count(); - println!("{} files, {jars} jars read", records.len()); - for (title, field) in [ - ( - "class", - (|r: &inventory::Record| r.class.as_str()) as fn(&inventory::Record) -> &str, - ), - ("tier", |r| r.tier.as_str()), - ("confidence", |r| r.confidence.as_str()), - ("source", |r| r.source.as_str()), - ] { - println!("{title}: {:?}", inventory::counts(&records, field)); - } - let layers = records.iter().map(|r| r.layer).max().map_or(0, |m| m + 1); - let per_layer: Vec = (0..layers) - .map(|l| records.iter().filter(|r| r.layer == l).count()) - .collect(); - println!("layers: {per_layer:?}"); - let missing: usize = records.iter().map(|r| r.missing.len()).sum(); - if missing > 0 { - println!("{missing} required dependencies are not in the pack (see inventory.json)"); - } - Ok(()) -} - -/// The vanilla blocks a prepared resource root has (`facts.json`'s defaults). -fn vanilla_blocks(resources: &Path) -> Result, String> { - let facts: serde_json::Value = read_json(&resources.join("facts.json"))?; - let defaults = facts["defaults"] - .as_object() - .ok_or("facts.json: no defaults")?; - Ok(defaults.keys().cloned().collect()) -} - -fn carry(work: &Path, resources: Option<&Path>, only: &[String]) -> Result<(), String> { - let records: Vec = read_json(&work.join("inventory.json"))?; - let facts_path = work.join("oracle/facts.json"); - let facts = if facts_path.exists() { - let f = oracle::Facts::read(&facts_path)?; - println!( - "oracle facts: {} blocks, {} items", - f.blocks.len(), - f.items.len() - ); - Some(f) - } else { - None - }; - let vanilla = resources.map(vanilla_blocks).transpose()?; - let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b)); - let mut done = 0; - for r in &records { - let chosen = if only.is_empty() { - r.class == "content" - } else { - only.contains(&r.key) - }; - let (Some(jar), Some(info)) = (&r.jar, &r.info) else { - if chosen && !only.is_empty() { - eprintln!("{}: no jar (put it in {}/jars/)", r.key, work.display()); - } - continue; - }; - if !chosen { - continue; - } - match carry::carry( - jar, - info, - &work.join("mods").join(&r.key), - facts.as_ref(), - &allowed, - ) { - Ok(report) => { - done += 1; - println!( - "{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded, {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside", - r.key, - report.copied, - report.recipes_upgraded, - report.recipes_kept.len(), - report.loot_tables_upgraded, - report.item_definitions_added, - report.blocks.len(), - report.blocks_unknown.len(), - report.differences.len(), - report.items, - report.items_unknown.len(), - report.convention_tags, - report.outside.len() - ); - } - Err(e) => eprintln!("{}: {e}", r.key), +/// Removes `--name ` from `args`. +fn option(args: &mut Vec, name: &str) -> Result, String> { + match args.iter().position(|a| a == name) { + Some(i) if i + 1 < args.len() => { + let value = args.remove(i + 1); + args.remove(i); + Ok(Some(PathBuf::from(value))) } + Some(_) => Err(USAGE.to_owned()), + None => Ok(None), } - println!( - "{done} mods carried over into {}", - work.join("mods").display() - ); - Ok(()) +} + +fn take_flag(args: &mut Vec, name: &str) -> bool { + let before = args.len(); + args.retain(|a| a != name); + args.len() != before } diff --git a/crates/horizon-port-pack/src/modrinth.rs b/crates/horizon-port-pack/src/modrinth.rs index 8c34a2004..4e90c871a 100644 --- a/crates/horizon-port-pack/src/modrinth.rs +++ b/crates/horizon-port-pack/src/modrinth.rs @@ -1,13 +1,13 @@ //! Modrinth metadata for the pack's files: the version of each file by -//! SHA-1, and its project (categories, licence, sides). Only metadata: no -//! jar is downloaded. Answers are cached in `/modrinth.json`, so a +//! SHA-1, and its project (categories, licence, sides). Only metadata (the +//! jars are `fetch`'s). Answers are cached in `/modrinth.json`, so a //! rerun works offline. use serde::{Deserialize, Serialize}; use serde_json::Value; use std::{collections::BTreeMap, path::Path}; const API: &str = "https://api.modrinth.com/v2"; -const AGENT: &str = "ludovic111/horizon horizon-port-pack/0.1 (docs/modpacks.md)"; +pub(crate) const AGENT: &str = "ludovic111/horizon horizon-port-pack/0.1 (docs/modpacks.md)"; #[derive(Debug, Default, Serialize, Deserialize)] pub struct Cache { diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs new file mode 100644 index 000000000..ddb39bf66 --- /dev/null +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -0,0 +1,237 @@ +//! The steps on a work folder, as the command line and the launcher run +//! them. Each one reads what the earlier steps wrote and says what it did +//! through `log`, one line at a time. +use crate::{carry, fetch, import, inventory, modrinth, oracle, report}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::Path, +}; + +/// Where a step's lines go: the terminal, or the launcher's log. +pub type Log<'a> = &'a dyn Fn(String); + +pub fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<(), String> { + let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; + fs::write(path, text).map_err(|e| format!("{}: {e}", path.display())) +} + +pub fn read_json(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) +} + +/// Step 1: the pack at `pack` to `/pack.json`. +pub fn import(pack: &Path, work: &Path, log: Log) -> Result { + let pack = import::import(pack)?; + fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?; + write_json(&work.join("pack.json"), &pack)?; + let mut kinds = BTreeMap::<&str, usize>::new(); + for f in &pack.files { + *kinds.entry(f.kind()).or_default() += 1; + } + log(format!( + "{} ({}): Minecraft {}, {} {}; files {kinds:?}; overrides {:?}", + pack.name, pack.format, pack.minecraft, pack.loader, pack.loader_version, pack.overrides + )); + Ok(pack) +} + +/// Step 2: `/inventory.json` and `inventory.csv`. Online, Modrinth is +/// asked about the files it has not answered for yet; when it cannot be +/// reached, the cached answers and the reviewed table classify alone. +pub fn inventory(work: &Path, offline: bool, log: Log) -> Result, String> { + let pack: import::Pack = read_json(&work.join("pack.json"))?; + let cache_path = work.join("modrinth.json"); + let mut cache = modrinth::Cache::load(&cache_path); + if !offline { + let hashes: Vec = pack.files.iter().filter_map(|f| f.sha1.clone()).collect(); + match cache.fetch(&hashes) { + Ok(()) => write_json(&cache_path, &cache)?, + Err(e) => log(format!("Modrinth not reached, classifying offline: {e}")), + } + } + let records = inventory::build(&pack, &cache, work); + write_json(&work.join("inventory.json"), &records)?; + fs::write(work.join("inventory.csv"), inventory::csv(&records)) + .map_err(|e| format!("inventory.csv: {e}"))?; + let jars = records.iter().filter(|r| r.jar.is_some()).count(); + log(format!("{} files, {jars} jars read", records.len())); + for (title, field) in [ + ( + "class", + (|r: &inventory::Record| r.class.as_str()) as fn(&inventory::Record) -> &str, + ), + ("tier", |r| r.tier.as_str()), + ("confidence", |r| r.confidence.as_str()), + ("source", |r| r.source.as_str()), + ] { + log(format!("{title}: {:?}", inventory::counts(&records, field))); + } + let layers = records.iter().map(|r| r.layer).max().map_or(0, |m| m + 1); + let per_layer: Vec = (0..layers) + .map(|l| records.iter().filter(|r| r.layer == l).count()) + .collect(); + log(format!("layers: {per_layer:?}")); + let missing: usize = records.iter().map(|r| r.missing.len()).sum(); + if missing > 0 { + log(format!( + "{missing} required dependencies are not in the pack (see inventory.json)" + )); + } + Ok(records) +} + +/// The vanilla blocks a prepared resource root has (`facts.json`'s defaults). +fn vanilla_blocks(resources: &Path) -> Result, String> { + let facts: serde_json::Value = read_json(&resources.join("facts.json"))?; + let defaults = facts["defaults"] + .as_object() + .ok_or("facts.json: no defaults")?; + Ok(defaults.keys().cloned().collect()) +} + +/// Step 4: the content mods with a jar (or the ones in `only`) carried over +/// into `/mods//carry/`. Returns how many were. +pub fn carry( + work: &Path, + resources: Option<&Path>, + only: &[String], + log: Log, +) -> Result { + let records: Vec = read_json(&work.join("inventory.json"))?; + let facts_path = work.join("oracle/facts.json"); + let facts = if facts_path.exists() { + let f = oracle::Facts::read(&facts_path)?; + log(format!( + "oracle facts: {} blocks, {} items", + f.blocks.len(), + f.items.len() + )); + Some(f) + } else { + None + }; + // Without the prepared tables, templates are not limited to what the game has. + let vanilla = resources.and_then(|r| { + vanilla_blocks(r) + .inspect_err(|e| log(format!("templates not limited to the game's blocks: {e}"))) + .ok() + }); + let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b)); + let mut done = 0; + for r in &records { + let chosen = if only.is_empty() { + r.class == "content" + } else { + only.contains(&r.key) + }; + let (Some(jar), Some(info)) = (&r.jar, &r.info) else { + if chosen && !only.is_empty() { + log(format!( + "{}: no jar (put it in {}/jars/)", + r.key, + work.display() + )); + } + continue; + }; + if !chosen { + continue; + } + match carry::carry( + jar, + info, + &work.join("mods").join(&r.key), + facts.as_ref(), + &allowed, + ) { + Ok(report) => { + done += 1; + log(format!( + "{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded, {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside", + r.key, + report.copied, + report.recipes_upgraded, + report.recipes_kept.len(), + report.loot_tables_upgraded, + report.item_definitions_added, + report.blocks.len(), + report.blocks_unknown.len(), + report.differences.len(), + report.items, + report.items_unknown.len(), + report.convention_tags, + report.outside.len() + )); + } + Err(e) => log(format!("{}: {e}", r.key)), + } + } + log(format!( + "{done} mods carried over into {}", + work.join("mods").display() + )); + Ok(done) +} + +/// The pack's title as the report heads it. +pub fn title(pack: &import::Pack) -> String { + format!( + "{} ({} {}, Minecraft {})", + pack.name, pack.loader, pack.loader_version, pack.minecraft + ) +} + +/// Step 7: `/coverage.json` and `coverage.md`. +pub fn report(work: &Path, log: Log) -> Result, String> { + let pack: import::Pack = read_json(&work.join("pack.json"))?; + let records: Vec = read_json(&work.join("inventory.json"))?; + let rows = report::build(&records, work); + write_json(&work.join("coverage.json"), &rows)?; + let title = title(&pack); + fs::write(work.join("coverage.md"), report::markdown(&title, &rows)) + .map_err(|e| format!("coverage.md: {e}"))?; + log(format!( + "{title}: {} files: {:?}", + rows.len(), + report::counts(&rows) + )); + Ok(rows) +} + +/// What a player's machine can port today without an agent: content mods +/// of the data tier (carry-over only). +pub fn portable(r: &inventory::Record) -> bool { + r.class == "content" && r.tier == "data" +} + +/// Everything after the import, for the portable mods: their jars (`fetch`, +/// from `from` when the player has them), the inventory again with the jars +/// read, the carry-over and the report. `resources` is the prepared +/// version the ports will play on. +pub fn port( + work: &Path, + resources: Option<&Path>, + from: Option<&Path>, + log: Log, +) -> Result<(fetch::Fetched, Vec), String> { + let records = match read_json::>(&work.join("inventory.json")) { + Ok(r) => r, + Err(_) => inventory(work, false, log)?, + }; + let fetched = fetch::fetch(work, &records, from, &portable, log)?; + // The jars tell classes and tiers better than metadata alone. + let records = inventory(work, true, log)?; + let only: Vec = records + .iter() + .filter(|r| portable(r) && r.jar.is_some()) + .map(|r| r.key.clone()) + .collect(); + if only.is_empty() { + log("no portable mod has its jar: nothing to carry over".into()); + } else { + carry(work, resources, &only, log)?; + } + Ok((fetched, report(work, log)?)) +} diff --git a/crates/horizon-port-pack/src/report.rs b/crates/horizon-port-pack/src/report.rs index ffa025c79..a98dd0432 100644 --- a/crates/horizon-port-pack/src/report.rs +++ b/crates/horizon-port-pack/src/report.rs @@ -83,7 +83,7 @@ pub fn license_kind(license: &str) -> &'static str { /// What still blocks a mod of this tier that has not been carried over. fn not_yet(tier: &str) -> &'static str { match tier { - "data" => "data tier: carry-over only, no agent; its jar is not in the work folder", + "data" => "data tier: carry-over only, no agent; its jar is not here yet (fetch gets it)", "logic" => { "needs mod API 0.3: behaviour callbacks (use, place, break, ticks) and server events" } diff --git a/docs/modpacks.md b/docs/modpacks.md index 1d8609cef..fb9bca5f4 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -267,16 +267,32 @@ inspected: └── coverage.json, coverage.md ``` -**Status.** `import`, `inventory`, `carry` and `report` run today: +**Status.** `import`, `inventory`, `fetch`, `carry` and `report` run today, and `port` runs +them all for what a player's machine can port (content mods of the data tier), as the +launcher's "Import modpack" does: ``` cargo run -p horizon-port-pack -- import ~/Downloads/pack.mrpack ~/.horizon/ports/pack cargo run -p horizon-port-pack -- inventory ~/.horizon/ports/pack # --offline reuses modrinth.json +cargo run -p horizon-port-pack -- fetch ~/.horizon/ports/pack # the portable mods' jars, or name them +# --from : copy the player's own jars (an installed instance, a downloads folder) cargo run -p horizon-port-pack -- carry ~/.horizon/ports/pack # content mods with a jar, or name them # --resources : only templates Horizon's tables have cargo run -p horizon-port-pack -- report ~/.horizon/ports/pack # coverage.json and coverage.md +cargo run -p horizon-port-pack -- port ~/Downloads/pack.zip ~/.horizon/ports/pack [--from ] [--resources ] ``` +`fetch` gets each jar the player's way, never from us: copied from a folder they have (matched +by SHA-1, or through a CurseForge app instance's `minecraftinstance.json`), else downloaded from +the link the pack itself gives (a `.mrpack`'s, on the format's hosts only) or, for a CurseForge +pack, the same file on Modrinth's public CDN, found by its SHA-1. A jar is kept only when its +hash matches. A file only CurseForge has is listed as needing a CurseForge API key (Ludovic's +decision; open question below), with the player's installed instance as the way round it. +`/fetch.json` says what happened to each file. On All the Mods 10 8.3's CurseForge zip +(2026-10-17): of the 54 data-tier content mods, 42 come from Modrinth's CDN (84 MB) and 12 need +the key or the instance; `port` then carries the 42 over (0 ported, 42 partial: the harness is a +dev step). + `inventory` reads metadata only: Modrinth answers by file hash, and the jars only if the user's instance has them (an imported instance folder, or jars put in `/jars/`). Without jars, classes come from the reviewed table, Modrinth categories and sides; with jars, from their @@ -310,7 +326,7 @@ block's name breaking ties (`_pane`, `_gate`, `_trapdoor`). | Format | Read | Jars come from | |---|---|---| | Modrinth `.mrpack` | `modrinth.index.json`: `dependencies` (minecraft, neoforge / fabric-loader / forge / quilt-loader), `files[]` with path, sha1/sha512, `env` (client/server), download URLs; `overrides/`, `client-overrides/`, `server-overrides/` | downloaded from the listed Modrinth URLs, hash-checked | -| CurseForge zip | `manifest.json`: `minecraft.version`, `modLoaders[]`, `files[]` (`projectID`, `fileID`, `required`), `overrides` | the user's installed instance (CurseForge app `minecraftinstance.json` + `mods/`). CurseForge's API needs a key, so we take what the user already downloaded | +| CurseForge zip | `manifest.json`: `minecraft.version`, `modLoaders[]`, `files[]` (`projectID`, `fileID`, `required`), `overrides`. When the overrides hold Crash Assistant's `config/crash_assistant/modlist.json` (All the Mods 10 does), its jar names, mod ids and SHA-1s replace the bare ids | the user's installed instance (CurseForge app `minecraftinstance.json` + `mods/`), or the same file on Modrinth by SHA-1. CurseForge's API needs a key, so we take what the user already downloaded | | Prism / MultiMC instance | `mmc-pack.json` components (`net.minecraft`, `net.neoforged`, `net.fabricmc.fabric-loader`), `instance.cfg`, `.minecraft/mods/*.jar`, packwiz `.pw.toml` files if present | the instance folder | | packwiz | `pack.toml`, `index.toml`, `mods/*.pw.toml` | as listed | | Crash Assistant `modlist.json` | jar name → mod id, name, version, Modrinth SHA-1; the loader entry (NeoForge `21.1.x` is Minecraft 1.21.1). Packs such as ATM10 publish it in their repository | metadata only; jars put in `/jars/` | From 206b91e8aa6576c2a5e5d7e0ed3695d33920c7e3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:00:45 +0200 Subject: [PATCH 024/327] Launcher: Import modpack, its coverage report, port and play it as a profile A Modpacks page between Versions and Patch notes (docs/modpacks.md, the working version's launcher step): - Import a pack file (.mrpack, CurseForge zip) or an instance folder (Prism, MultiMC, CurseForge): horizon-port-pack's import, inventory (Modrinth by file hash) and report into ports// in the game's home. - The coverage report: ported, partial, not yet and not needed, with every mod's class, tier, licence and reason, filtered by status. - Port: the portable mods' jars (content, data tier) the player's own way (their folder, the pack's links, Modrinth's CDN; what only CurseForge has needs its key and is said so), carried over for the selected version's prepared tables; the pipeline's log shows while it runs. - Play: the game as the pack's own profile, ports//home/ (its saves, options.txt copied from the player's the first time) with the carried-over mods as dev mods. The session flow is shared with Play (start_client). - The same from the command line: horizon-launcher modpack list | import | port | play | remove. Nothing is uploaded or shared; jars and ports stay in the game's home. Co-Authored-By: Claude Opus 5.5 --- launcher/Cargo.lock | 13 ++ launcher/Cargo.toml | 2 + launcher/README.md | 18 +- launcher/docs/modpacks.png | Bin 0 -> 113972 bytes launcher/src/backend.rs | 4 + launcher/src/cli.rs | 104 +++++++++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 105 ++++++--- launcher/src/modpacks.rs | 249 ++++++++++++++++++++ launcher/src/modpacks_page.rs | 412 ++++++++++++++++++++++++++++++++++ 10 files changed, 875 insertions(+), 33 deletions(-) create mode 100644 launcher/docs/modpacks.png create mode 100644 launcher/src/modpacks.rs create mode 100644 launcher/src/modpacks_page.rs diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 4a281729d..af0588af6 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2664,6 +2664,7 @@ dependencies = [ "gpui", "horizon-bench", "horizon-friends", + "horizon-port-pack", "horizon-prepare", "horizon-telemetry", "horizon-theme", @@ -2680,6 +2681,18 @@ dependencies = [ "zip", ] +[[package]] +name = "horizon-port-pack" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "sha1", + "toml 1.1.8+spec-1.1.0", + "ureq", + "zip", +] + [[package]] name = "horizon-prepare" version = "0.1.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 8f5873f87..34af6e2a1 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -26,6 +26,8 @@ horizon-prepare = { path = "../crates/horizon-prepare" } # Join a friend: invite codes (the game does the joining). horizon-friends = { path = "../crates/horizon-friends" } horizon-bench = { path = "../crates/horizon-bench" } +# Import modpack: the porting pipeline, run on the player's own files (docs/modpacks.md). +horizon-port-pack = { path = "../crates/horizon-port-pack" } # Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md). horizon-telemetry = { path = "../crates/horizon-telemetry" } # The session file's random name. diff --git a/launcher/README.md b/launcher/README.md index e5edba182..b3dff7fde 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -25,6 +25,16 @@ The opening, then Play ([clip](docs/opening.webm)): preparation reuses checksum-verified game jars and libraries from the current or another installed Horizon version, so the original Minecraft install is only required when no valid imported copy exists. +- **Modpacks**: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, or a Prism, + MultiMC or CurseForge instance folder) and see its coverage report: per mod, ported, partial, + not yet or not needed, with the reason ([docs/modpacks.md](../docs/modpacks.md)). **Port** + gets the jars of what this computer can port today (content mods with data and assets only) + the player's own way: copied from a folder they have, or downloaded from the pack's own links + or the same file on Modrinth's CDN, hash checked; files only CurseForge has need its API key, so + they come from your installed instance. It carries them over for the selected version, and + **Play** starts the game as the pack's own profile (`ports//home/` in the game's home: + its own saves and options) with those mods. Nothing is uploaded or shared: mod jars and ports + stay on this computer. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, @@ -83,6 +93,11 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher account sign-out horizon-launcher account select play as this account horizon-launcher account offline play without an account + horizon-launcher modpack [list] the imported packs and their coverage + horizon-launcher modpack import a .mrpack, CurseForge zip or instance folder + horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over + horizon-launcher modpack play [--version ] play it as its own profile + horizon-launcher modpack remove horizon-launcher benchmark [--repeats N] measure the launcher (see Performance log) horizon-launcher data [status] what data collection is allowed, the install ID, what waits horizon-launcher data allow|deny performance, crashes, bugs, benchmarks @@ -92,7 +107,7 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher data benchmark upload a benchmark report, printed first `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). @@ -192,6 +207,7 @@ bundled so the type is the same on every platform. ## Screenshots ![Server](docs/server.png) +![Modpacks](docs/modpacks.png) ![Versions](docs/versions.png) ![Patch notes](docs/patch-notes.png) ![Settings](docs/settings.png) diff --git a/launcher/docs/modpacks.png b/launcher/docs/modpacks.png new file mode 100644 index 0000000000000000000000000000000000000000..9abe41c64a59ff5e837c8768f56eb4aa2671a38a GIT binary patch literal 113972 zcmdqJbySpZ6fTOQ0+Nb^AmE6Cv~)890@BjWDBT^>DoA%X64D{vAV}BH-Q5iX3~^rL zx6Zx)-F4Sl=dN={*Ya~1zWL^R_q+GApXb@*_fAF(`##Bi6ciL}@wac}QBdxFLqS1Z zN52i8$$H$E0seWa`&M2W1;v>P1?7_$3d#j|>eD(3iv24Tl+E`jC_J$!C`49?HFA95 z2lsR&#onOY{QmQ;J}Uye5=H!tpyJ2L?HNPOM`9Fc`_;V8d-aIfH?NBw?<#I<;p4MY zkw}-1We>!T>kMZXBSZ=A+<9{=OgjTH>*7=EqMcuz$kt>;j_WZO!eoIkFf=qYP&xG| zEiF4emHB;c8WU>Hs>#O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d24S2qt@c&R#%_U8@; zEj~AxrVR^`cypYa+eM~q^olsb0&Lsw0^8cyx(4;PHyw_MUB8T@GujvTxL`sb*J~-# zy3ftd%p*k`8lDVyyGEPb_+D)bUa-TX0n3NL-d)}AUaj+RXX5slVlYrWf%c?fpW{I}fw-B3{ z;pEi|iwFx2N;x=*@C0gfa{g`(c}S=xlGj2?3Fw8>9@cL?DmiL7(mIZF#r{Dx(WiU!o+?2vAqM@QC1KZf^=vht1B`0NqNlFd zT5K!tjeLVb&$%+f5_5So11hL)BMqMx&yDLM6`lkpMOS*BHlvZx?$D>8;o zLweb2rGG!8yUL9WTHB!4LTyRT^Az2*Jq%Y6xrceCin^s`Rd$j8&x3O2OnfO`-G$$_ jI+#pC&;GwtC1X)`AuS_6?WY%i&5}, String>), + /// A modpack step's line (`modpacks`). + PackLine(String), + /// A modpack step ended: the pack as it now is. + PackDone(Result, String>), } /// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`. diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index df9cfc6b1..b140979b3 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -76,6 +76,33 @@ enum DataCmd { }, } +#[derive(Subcommand)] +enum ModpackCmd { + /// The imported packs and their coverage (the default) + List, + /// Import a .mrpack, a CurseForge zip or an instance folder, and write its coverage report + Import { path: PathBuf }, + /// Get the jars of what this computer can port and carry them over + Port { + /// The pack's folder name, as list shows it + pack: String, + /// A folder with your own jars (an installed instance, a downloads folder) + #[arg(long)] + from: Option, + /// The installed version the ports are for (default: the selected one) + #[arg(long)] + version: Option, + }, + /// Play a ported pack as its own profile + Play { + pack: String, + #[arg(long)] + version: Option, + }, + /// Remove an imported pack: its jars, ports and the profile's saves + Remove { pack: String }, +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -161,6 +188,12 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// Modpacks: import a Java pack, see its coverage report, port what this computer can and + /// play it as its own profile (docs/modpacks.md) + Modpack { + #[command(subcommand)] + action: Option, + }, /// Serve the Model Context Protocol on stdin and stdout, for AI agents Mcp, /// Measure the launcher: starts (the first is the cold one), page switching, idle CPU and @@ -400,6 +433,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("Horizon is in the applications menu."); } } + Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, Cmd::Mcp => unreachable!(), } Ok(()) @@ -591,3 +625,73 @@ fn data(action: DataCmd, as_json: bool) -> Result<(), String> { } Ok(()) } + +fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { + use horizon_launcher::modpacks::{self, Imported}; + use horizon_port_pack::report::Status; + let log = &|line: String| eprintln!("{line}"); + let work = |pack: &str| { + let work = modpacks::ports_dir().join(pack); + modpacks::load(&work).map(|_| work) + }; + let show = |p: &Imported| { + let counts: Vec = Status::ALL + .iter() + .map(|s| format!("{} {}", p.count(*s), s.label())) + .collect(); + if as_json { + json(serde_json::json!({ + "pack": p.slug, "name": p.title(), "summary": p.summary(), + "counts": Status::ALL.iter().map(|s| (s.label(), p.count(*s))).collect::>(), + "portable": p.portable, "ported_mods": p.mods.len(), "jars": p.jars(), + "report": p.work.join("coverage.md"), + })); + } else { + println!( + "{} ({})\n {}\n {}", + p.title(), + p.slug, + p.summary(), + counts.join(", ") + ); + println!(" {} portable, {} carried over", p.portable, p.mods.len()); + if let Some(jars) = p.jars() { + println!(" {jars}"); + } + println!(" {}", p.work.join("coverage.md").display()); + } + }; + match action { + ModpackCmd::List => { + let packs = modpacks::list(); + if packs.is_empty() && !as_json { + println!("No modpack imported yet: horizon-launcher modpack import "); + } + packs.iter().for_each(show); + } + ModpackCmd::Import { path } => show(&modpacks::import(&path, log)?), + ModpackCmd::Port { + pack, + from, + version, + } => { + let tag = backend::resolve_version(version.as_deref()).ok(); + let resources = tag + .filter(|t| backend::is_prepared(t)) + .map(|t| backend::resources(&t)); + show(&modpacks::port( + &work(&pack)?, + resources.as_deref(), + from.as_deref(), + log, + )?) + } + ModpackCmd::Play { pack, version } => { + let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; + modpacks::apply_profile(&mut cmd, &work(&pack)?)?; + attached(cmd)? + } + ModpackCmd::Remove { pack } => modpacks::remove(&work(&pack)?)?, + } + Ok(()) +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 5df6a7cbb..11023a46d 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -2,6 +2,7 @@ pub mod account; pub mod backend; pub mod desktop; +pub mod modpacks; pub mod mojang; pub mod sources; pub mod telemetry; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index cc66aa08e..ec1dacf78 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -6,6 +6,7 @@ mod collection; mod game_tools; mod markdown; mod mcp; +mod modpacks_page; mod perf; mod theme; @@ -29,14 +30,16 @@ use theme::Theme; enum Page { Play, Versions, + Modpacks, Notes, Settings, } impl Page { - const ALL: [(Page, &'static str); 4] = [ + const ALL: [(Page, &'static str); 5] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), + (Page::Modpacks, "Modpacks"), (Page::Notes, "Patch notes"), (Page::Settings, "Settings"), ]; @@ -161,6 +164,17 @@ struct Launcher { play_pressed: Option, /// `horizon-launcher benchmark` started this window to measure it. bench: Option, + /// The Modpacks page: the imported packs (read when the page first opens), the one shown, + /// the report's filter, and the pipeline step running now with its log. + packs: Vec, + packs_loaded: Option, + pack_open: Option, + pack_filter: Option, + pack_busy: bool, + pack_log: VecDeque, + pack_error: Option, + /// The game starting now plays this pack's profile (its work folder). + starting_pack: Option, } impl Launcher { @@ -266,6 +280,14 @@ impl Launcher { prepare_started: None, play_pressed: None, bench: perf::Bench::from_env(), + packs: Vec::new(), + packs_loaded: None, + pack_open: None, + pack_filter: None, + pack_busy: false, + pack_log: VecDeque::new(), + pack_error: None, + starting_pack: None, }; if this.bench.is_some() { this.perf.keep_local_log(false); @@ -406,6 +428,14 @@ impl Launcher { Err(e) => self.client_error = Some(format!("Playing offline: {e}")), } self.accounts = Accounts::load(); + if let Some(work) = self.starting_pack.take() { + if let Err(e) = + horizon_launcher::modpacks::apply_profile(&mut cmd, &work) + { + self.client_error = Some(e); + continue; + } + } if let Some(code) = self.joining.take() { if let Err(e) = backend::join_friend(&mut cmd, &code) { self.client_error = Some(e); @@ -473,6 +503,13 @@ impl Launcher { Err(e) => SelfUpdate::Failed(e), }; } + Msg::PackLine(line) => { + self.pack_log.push_back(line); + if self.pack_log.len() > LOG_LINES { + self.pack_log.pop_front(); + } + } + Msg::PackDone(result) => self.pack_done(result), Msg::Line(job, line) => { if job == Job::Client && line.starts_with(perf::GAME_FIRST_FRAME) { if let Some(pressed) = self.play_pressed.take() { @@ -671,37 +708,8 @@ impl Launcher { if self.client.is_some() || self.starting_client.is_some() { return; } - self.client_error = None; - self.crash = None; - self.prepare_log.clear(); - // A little earlier than the spawn: file times can be coarse. - self.client_started = - Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); - // The session (a network round trip when the token needs renewing) comes first; - // `drain` starts the game when it arrives. - self.starting_client = Some(tag); - self.play_pressed = Some(Instant::now()); - let tx = self.tx.clone(); - std::thread::spawn(move || { - let session = (|| { - let mut accounts = Accounts::load(); - let Some((a, secrets)) = account::session_for_launch( - &account::Endpoints::live(), - account::store(), - &mut accounts, - )? - else { - return Ok(None); - }; - account::write_session_file( - &backend::game_home().join("sessions"), - &a, - &secrets, - ) - .map(Some) - })(); - let _ = tx.send(Msg::Session(session)); - }); + self.starting_pack = None; + self.start_client(tag); } Mode::Server => { if let Some(server) = &mut self.server { @@ -729,6 +737,38 @@ impl Launcher { } } + /// Starts the game: the session first (a network round trip when the token needs + /// renewing), then `drain` starts the process when it arrives. + fn start_client(&mut self, tag: String) { + self.client_error = None; + self.crash = None; + self.prepare_log.clear(); + // A little earlier than the spawn: file times can be coarse. + self.client_started = + Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); + // The session (a network round trip when the token needs renewing) comes first; + // `drain` starts the game when it arrives. + self.starting_client = Some(tag); + self.play_pressed = Some(Instant::now()); + let tx = self.tx.clone(); + std::thread::spawn(move || { + let session = (|| { + let mut accounts = Accounts::load(); + let Some((a, secrets)) = account::session_for_launch( + &account::Endpoints::live(), + account::store(), + &mut accounts, + )? + else { + return Ok(None); + }; + account::write_session_file(&backend::game_home().join("sessions"), &a, &secrets) + .map(Some) + })(); + let _ = tx.send(Msg::Session(session)); + }); + } + fn choose_folder(&mut self, server: bool, cx: &mut Context) { let paths = cx.prompt_for_paths(PathPromptOptions { files: false, @@ -2774,6 +2814,7 @@ impl Render for Launcher { let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), + Page::Modpacks => self.modpacks_page(cx), Page::Notes => self.notes_page(cx), Page::Settings => self.settings_page(cx), }; diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs new file mode 100644 index 000000000..6d4553a14 --- /dev/null +++ b/launcher/src/modpacks.rs @@ -0,0 +1,249 @@ +//! Modpacks: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, an instance folder), +//! show what Horizon runs of it, port that on this computer from the player's own downloads, and +//! play it as a profile of its own (docs/modpacks.md). +//! +//! Each pack lives in `ports//` in the game's home: the work folder `horizon-port-pack` +//! writes (pack.json, inventory, the jars, the carried-over mods, the coverage report) and +//! `home/`, the profile's own saves and options. Nothing is uploaded or shared: mod jars are +//! often All Rights Reserved, so the ports stay on the player's machine. +use crate::backend; +use horizon_port_pack::{ + fetch::{Fetched, How}, + import::Pack, + pipeline::{self, Log}, + report::{Row, Status}, +}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Where imported packs live. +pub fn ports_dir() -> PathBuf { + backend::game_home().join("ports") +} + +/// A pack's folder name: its name in lowercase words joined by dashes. +pub fn slug(name: &str) -> String { + let words: Vec = name + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_ascii_lowercase) + .collect(); + if words.is_empty() { + "pack".into() + } else { + words.join("-") + } +} + +/// An imported pack, as its work folder has it. +pub struct Imported { + pub slug: String, + pub work: PathBuf, + pub pack: Pack, + pub rows: Vec, + pub fetched: Fetched, + /// The carried-over mods the profile loads. + pub mods: Vec, + /// The mods the port step gets and carries over (content, data tier). + pub portable: usize, +} + +impl Imported { + pub fn title(&self) -> &str { + if self.pack.name.is_empty() { + &self.slug + } else { + &self.pack.name + } + } + pub fn count(&self, status: Status) -> usize { + self.rows.iter().filter(|r| r.status == status).count() + } + /// "Minecraft 1.21.1 · neoforge 21.1.259 · 496 mods". + pub fn summary(&self) -> String { + let mut parts = Vec::new(); + if !self.pack.minecraft.is_empty() { + parts.push(format!("Minecraft {}", self.pack.minecraft)); + } + if !self.pack.loader.is_empty() { + parts.push(format!("{} {}", self.pack.loader, self.pack.loader_version)); + } + parts.push(format!("{} files", self.pack.files.len())); + parts.join(" · ") + } + /// What getting the jars did, in one line, or None before it ran. + pub fn jars(&self) -> Option { + if self.fetched.files.is_empty() { + return None; + } + let mut parts = Vec::new(); + for (how, what) in [ + (How::Downloaded, "downloaded"), + (How::Local, "copied from your folder"), + (How::Present, "already here"), + ( + How::NeedsKey, + "only on CurseForge (needs its API key: choose your installed instance instead)", + ), + (How::NotFound, "not found"), + (How::Failed, "failed"), + ] { + let n = self.fetched.count(how); + if n > 0 { + parts.push(format!("{n} {what}")); + } + } + Some(format!("Jars: {}.", parts.join(", "))) + } +} + +/// Reads the pack in `work`. +pub fn load(work: &Path) -> Result { + let pack: Pack = pipeline::read_json(&work.join("pack.json"))?; + let rows: Vec = pipeline::read_json(&work.join("coverage.json")).unwrap_or_default(); + let records: Vec = + pipeline::read_json(&work.join("inventory.json")).unwrap_or_default(); + Ok(Imported { + slug: work + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + work: work.to_path_buf(), + pack, + rows, + fetched: Fetched::load(work), + mods: carried(work), + portable: records.iter().filter(|r| pipeline::portable(r)).count(), + }) +} + +/// Every imported pack, by name. +pub fn list() -> Vec { + let mut packs: Vec = fs::read_dir(ports_dir()) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| load(&e.path()).ok()) + .collect(); + packs.sort_by_key(|p| p.title().to_ascii_lowercase()); + packs +} + +/// The carried-over mods in a work folder (`mods//carry/` with its manifest). +pub fn carried(work: &Path) -> Vec { + let mut mods: Vec = fs::read_dir(work.join("mods")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path().join("carry")) + .filter(|c| c.join("horizon-mod.toml").is_file()) + .collect(); + mods.sort(); + mods +} + +/// Imports the pack at `path` into `ports//` and writes its coverage report from +/// metadata (Modrinth answers by file hash; nothing is downloaded yet). Importing the same pack +/// again keeps the jars and ports it already has. +pub fn import(path: &Path, log: Log) -> Result { + let pack = horizon_port_pack::import::import(path)?; + let name = if pack.name.is_empty() || pack.name == "modlist" { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + } else { + pack.name.clone() + }; + let work = ports_dir().join(slug(&name)); + log(format!("Importing {name} into {}", work.display())); + pipeline::import(path, &work, log)?; + pipeline::inventory(&work, false, log)?; + pipeline::report(&work, log)?; + load(&work) +} + +/// Ports what this computer can: the portable mods' jars (from `from` when the player has them, +/// else the pack's links or Modrinth), carried over for `resources`, then the report again. +pub fn port( + work: &Path, + resources: Option<&Path>, + from: Option<&Path>, + log: Log, +) -> Result { + pipeline::port(work, resources, from, log)?; + load(work) +} + +/// Removes an imported pack: its jars, ports and the profile's saves. +pub fn remove(work: &Path) -> Result<(), String> { + if work.parent() != Some(ports_dir().as_path()) { + return Err(format!("{} is not an imported pack", work.display())); + } + fs::remove_dir_all(work).map_err(|e| format!("{}: {e}", work.display())) +} + +/// The profile's own game home: saves, options.txt, logs. +pub fn profile_home(work: &Path) -> PathBuf { + work.join("home") +} + +/// Turns the game's command into this pack's profile: its own home (the player's options.txt +/// copied in the first time, so keys and video settings carry over) and its carried-over mods. +pub fn apply_profile(cmd: &mut Command, work: &Path) -> Result<(), String> { + let mods = carried(work); + if mods.is_empty() { + return Err("Nothing is ported yet: port the pack first.".into()); + } + let home = profile_home(work); + fs::create_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?; + let options = home.join("options.txt"); + let own = backend::game_home().join("options.txt"); + if !options.exists() && own.is_file() { + let _ = fs::copy(own, &options); + } + cmd.current_dir(&home).env("HORIZON_HOME", &home); + for m in mods { + cmd.arg("--dev-mod").arg(m); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slugs() { + assert_eq!(slug("All the Mods 10"), "all-the-mods-10"); + assert_eq!(slug("Create: Above & Beyond!"), "create-above-beyond"); + assert_eq!(slug(" "), "pack"); + } + + #[test] + fn a_profile_has_its_own_home_and_mods() { + let root = + std::env::temp_dir().join(format!("horizon-launcher-pack-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let work = root.join("ports/small"); + let mut cmd = Command::new("true"); + assert!(apply_profile(&mut cmd, &work).is_err()); + for id in ["a", "b"] { + let carry = work.join("mods").join(id).join("carry"); + fs::create_dir_all(&carry).unwrap(); + fs::write(carry.join("horizon-mod.toml"), "").unwrap(); + } + // Left out: no manifest. + fs::create_dir_all(work.join("mods/c/carry")).unwrap(); + apply_profile(&mut cmd, &work).unwrap(); + let args: Vec = cmd + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + assert_eq!(args.len(), 4); + assert!(args[1].ends_with("a/carry") && args[3].ends_with("b/carry")); + assert_eq!(cmd.get_current_dir(), Some(profile_home(&work).as_path())); + assert!(profile_home(&work).is_dir()); + fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/launcher/src/modpacks_page.rs b/launcher/src/modpacks_page.rs new file mode 100644 index 000000000..2398421c6 --- /dev/null +++ b/launcher/src/modpacks_page.rs @@ -0,0 +1,412 @@ +//! The Modpacks page: import a pack, read its coverage report, port what this computer can and +//! play it as its own profile (`horizon_launcher::modpacks`). +use super::*; +use horizon_launcher::modpacks::{self, Imported}; +use horizon_port_pack::report::Status; +use std::path::PathBuf; + +/// The report's filter: every row, or one status. +pub(super) const FILTERS: [(Option, &str); 5] = [ + (None, "All"), + (Some(Status::Ported), "Ported"), + (Some(Status::Partial), "Partial"), + (Some(Status::NotYet), "Not yet"), + (Some(Status::NotNeeded), "Not needed"), +]; + +/// Lines of the pipeline's log the page shows while it works. +const LOG_SHOWN: usize = 6; + +impl Launcher { + fn open_pack(&self) -> Option<&Imported> { + let slug = self.pack_open.as_ref()?; + self.packs.iter().find(|p| &p.slug == slug) + } + + /// Runs a pipeline step on a thread; its lines and its end arrive as messages. + fn pack_job( + &mut self, + job: impl FnOnce(&dyn Fn(String)) -> Result + Send + 'static, + ) { + if self.pack_busy { + return; + } + self.pack_busy = true; + self.pack_log.clear(); + self.pack_error = None; + let tx = self.tx.clone(); + std::thread::spawn(move || { + let lines = tx.clone(); + let log = move |line: String| { + let _ = lines.send(Msg::PackLine(line)); + }; + let result = job(&log); + let _ = tx.send(Msg::PackDone(result.map(Box::new))); + }); + } + + /// A finished step: the pack's new state, opened. + pub(super) fn pack_done(&mut self, result: Result, String>) { + self.pack_busy = false; + match result { + Ok(pack) => { + self.pack_open = Some(pack.slug.clone()); + self.packs.retain(|p| p.slug != pack.slug); + self.packs.push(*pack); + self.packs.sort_by_key(|p| p.title().to_ascii_lowercase()); + } + Err(e) => self.pack_error = Some(e), + } + } + + fn choose_pack(&mut self, folder: bool, cx: &mut Context) { + let paths = cx.prompt_for_paths(PathPromptOptions { + files: !folder, + directories: folder, + multiple: false, + prompt: Some("Import".into()), + }); + cx.spawn(async move |this, cx| { + if let Ok(Ok(Some(mut paths))) = paths.await { + if let Some(path) = paths.pop() { + let _ = this.update(cx, |this, cx| { + this.pack_job(move |log| modpacks::import(&path, log)); + cx.notify(); + }); + } + } + }) + .detach(); + } + + /// Ports the open pack; `from` is a folder of the player's jars, chosen when `ask`. + fn port_pack(&mut self, ask: bool, cx: &mut Context) { + let Some(work) = self.open_pack().map(|p| p.work.clone()) else { + return; + }; + let resources = self + .selected() + .filter(|tag| backend::is_prepared(tag)) + .map(|tag| backend::resources(tag)); + if !ask { + self.pack_job(move |log| modpacks::port(&work, resources.as_deref(), None, log)); + return; + } + let paths = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Use these jars".into()), + }); + cx.spawn(async move |this, cx| { + if let Ok(Ok(Some(mut paths))) = paths.await { + if let Some(from) = paths.pop() { + let _ = this.update(cx, |this, cx| { + this.pack_job(move |log| { + modpacks::port(&work, resources.as_deref(), Some(&from), log) + }); + cx.notify(); + }); + } + } + }) + .detach(); + } + + fn play_pack(&mut self, work: PathBuf) { + let Some(tag) = self.selected().cloned() else { + return; + }; + if self.client.is_some() || self.starting_client.is_some() { + return; + } + self.starting_pack = Some(work); + self.start_client(tag); + } + + pub(super) fn modpacks_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if self.packs_loaded.is_none() { + self.packs = modpacks::list(); + if self.pack_open.is_none() { + self.pack_open = self.packs.first().map(|p| p.slug.clone()); + } + self.packs_loaded = Some(Instant::now()); + } + let header = page_header( + "Modpacks", + "Bring a Java modpack: see what Horizon runs of it, port that on this computer from \ + your own downloads, and play it as its own profile. Nothing is uploaded or shared.", + &t, + ); + let busy = self.pack_busy; + let pick = |id: &'static str, label: &'static str, folder: bool| { + let b = button(id, label, Kind::Secondary, &t); + if busy { + disabled(b) + } else { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.choose_pack(folder, cx); + cx.notify(); + })) + } + }; + let actions = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .child(pick("import-file", "Import a pack file…", false)) + .child(pick("import-folder", "Import an instance folder…", true)) + .child(text(theme::CAPTION).text_color(t.muted).child( + ".mrpack (Modrinth), .zip (CurseForge), or a Prism, MultiMC or CurseForge instance", + )); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(actions); + if busy || !self.pack_log.is_empty() { + page = page.child(self.pack_log_plate(&t)); + } + if let Some(e) = &self.pack_error { + page = page.child(notice(e.clone(), &t)); + } + if self.packs.is_empty() { + return page.child(centered( + "No modpack yet. Import one to see what Horizon can run of it.", + &t, + )); + } + if self.packs.len() > 1 { + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in self.packs.iter().enumerate() { + let open = self.pack_open.as_ref() == Some(&p.slug); + let slug = p.slug.clone(); + let right = if open { + caps("Open").text_color(t.accent).into_any_element() + } else { + button(format!("open-{slug}"), "Open", Kind::Ghost, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.pack_open = Some(slug.clone()); + cx.notify(); + })) + .into_any_element() + }; + list = list.child(index_row( + i + 1, + p.title().to_string(), + Some(p.summary().into_any_element()), + Some(right), + &t, + )); + } + page = page.child(list); + } + match self.pack_detail(cx) { + Some(detail) => page.child(detail), + None => page, + } + } + + fn pack_log_plate(&self, t: &Theme) -> Div { + let start = self.pack_log.len().saturating_sub(LOG_SHOWN); + plate(t) + .flex() + .flex_col() + .gap(px(4.)) + .p(px(16.)) + .child( + caps(if self.pack_busy { "Working" } else { "Done" }) + .text_color(if self.pack_busy { t.accent } else { t.muted }), + ) + .children(self.pack_log.iter().skip(start).map(|line| { + text(theme::CAPTION) + .font_family(theme::MONO) + .text_color(t.ink_soft) + .truncate() + .child(line.clone()) + })) + } + + fn pack_detail(&self, cx: &mut Context) -> Option

{ + let t = self.theme; + let p = self.open_pack()?; + let mut counts = div().flex().gap(px(12.)); + for (status, label) in FILTERS.iter().skip(1) { + let status = status.expect("the first filter is All"); + let color = match status { + Status::Ported => t.success, + Status::Partial => t.accent, + _ => t.ink, + }; + counts = counts.child( + plate(&t) + .flex() + .flex_col() + .flex_1() + .gap(px(4.)) + .p(px(16.)) + .child( + text(theme::DISPLAY) + .text_color(color) + .child(p.count(status).to_string()), + ) + .child(caps(*label).text_color(t.muted)), + ); + } + let can_play = self.selected().is_some_and(|tag| backend::is_prepared(tag)); + let running = self.client.is_some() || self.starting_client.is_some(); + let mut buttons = div().flex().flex_wrap().items_center().gap(px(8.)); + let play_label = if p.mods.is_empty() { + "Play".to_string() + } else { + format!("Play with {} mods", p.mods.len()) + }; + let mut play = button("pack-play", play_label, Kind::Primary, &t); + if p.mods.is_empty() || !can_play || running || self.pack_busy { + play = disabled(play); + } else { + let work = p.work.clone(); + play = play.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.play_pack(work.clone()); + cx.notify(); + })); + } + let port_label = format!("Port {} mods", p.portable); + let mut port = button("pack-port", port_label, Kind::Secondary, &t); + let mut from = button("pack-from", "Use jars from my instance…", Kind::Ghost, &t); + if self.pack_busy || p.portable == 0 { + port = disabled(port); + from = disabled(from); + } else { + port = port.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.port_pack(false, cx); + cx.notify(); + })); + from = from.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.port_pack(true, cx); + cx.notify(); + })); + } + let confirming = self.confirm_remove.as_deref() == Some(p.slug.as_str()); + let slug = p.slug.clone(); + let work = p.work.clone(); + let remove = button( + "pack-remove", + if confirming { + "Remove for good" + } else { + "Remove" + }, + if confirming { + Kind::Secondary + } else { + Kind::Ghost + }, + &t, + ) + .when(confirming, |b| b.text_color(t.danger)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if this.confirm_remove.as_ref() == Some(&slug) { + match modpacks::remove(&work) { + Ok(()) => { + this.packs.retain(|p| p.slug != slug); + this.pack_open = this.packs.first().map(|p| p.slug.clone()); + } + Err(e) => this.pack_error = Some(e), + } + this.confirm_remove = None; + } else { + this.confirm_remove = Some(slug.clone()); + } + cx.notify(); + })); + buttons = buttons.child(play).child(port).child(from).child(remove); + let mut notes = vec![format!( + "Port gets the jars of the {} mods this computer can port today (content with data \ + and assets only) from the pack's own links, Modrinth, or your folder, and carries \ + them over. The ports stay here, in {}.", + p.portable, + short(&p.work) + )]; + if let Some(jars) = p.jars() { + notes.push(jars); + } + if !can_play { + notes.push("Playing needs a prepared Horizon version (Play page).".into()); + } + let mut rows: Vec<&horizon_port_pack::report::Row> = p + .rows + .iter() + .filter(|r| self.pack_filter.is_none_or(|s| r.status == s)) + .collect(); + rows.sort_by(|a, b| (a.status, &a.key).cmp(&(b.status, &b.key))); + let filter = segments("pack-filter", &FILTERS, self.pack_filter, &t, { + let this = cx.entity().downgrade(); + move |value, _, cx| { + let _ = this.update(cx, |this, cx| { + this.pack_filter = value; + cx.notify(); + }); + } + }); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, r) in rows.iter().enumerate() { + let color = match r.status { + Status::Ported => t.success, + Status::Partial => t.accent, + Status::NotYet => t.ink_soft, + Status::NotNeeded => t.muted, + }; + let name = if r.name.is_empty() || r.name == r.key { + r.key.clone() + } else { + format!("{} ({})", r.name, r.key) + }; + let detail = format!("{} · {} · {}: {}", r.class, r.tier, r.license, r.reason); + list = list.child(index_row( + i + 1, + name, + Some(detail.into_any_element()), + Some( + caps(r.status.label()) + .flex_none() + .text_color(color) + .into_any_element(), + ), + &t, + )); + } + Some( + div() + .flex() + .flex_col() + .gap(px(24.)) + .child( + div() + .flex() + .flex_col() + .gap(px(4.)) + .child( + text(theme::TITLE) + .text_color(t.ink) + .child(p.title().to_string()), + ) + .child(text(theme::UI).text_color(t.muted).child(p.summary())), + ) + .child(counts) + .child(buttons) + .children(self.client_error.clone().map(|e| notice(e, &t))) + .children(notes.into_iter().map(|n| { + text(theme::CAPTION) + .max_w(px(720.)) + .text_color(t.muted) + .child(n) + })) + .child(div().flex().child(filter)) + .child(list), + ) + } +} From 56a49895602d9bcdd5a7b57c4a82d2a4755bab1d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:02:33 +0200 Subject: [PATCH 025/327] Network client: show the server's advancements and statistics ClientboundUpdateAdvancementsPacket and ClientboundAwardStatsPacket are new in the protocol crate, and the window applies them as vanilla's client does: - ClientAdvancements.update: a reset replaces the tree, added advancements join it with their place on the tab (DisplayInfo x, y), removed ones go, each changed one takes the progress sent, and one that is done in a non-reset update with show set gets its toast. The advancements screen lays a server's tree out where the server placed it and shows everything it sent. - handleAwardStats: the counters the server sends, by registry name. Opening the statistics screen asks for them (StatsScreen.init's REQUEST_STATS). Joining and leaving a server start from empty advancements and statistics. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/advancements.rs | 107 +++++++++ .../src/game/advancements_screen.rs | 24 +- crates/horizon-client/src/game/remote.rs | 45 ++++ .../horizon-client/src/game/stats_screen.rs | 6 + crates/horizon-protocol/src/item.rs | 36 +++ crates/horizon-protocol/src/packets/play.rs | 220 ++++++++++++++++++ 6 files changed, 432 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 980b5769e..3b52b3df9 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -72,6 +72,9 @@ impl Toast { #[derive(Default)] pub(super) struct AdvState { pub(super) tree: Arc, + /// `ClientAdvancements`: a server's tree carries each advancement's + /// place on its tab (`DisplayInfo` x, y), in tree order. + pub(super) positions: Option>, pub(super) progress: Progress, pub(super) loaded: bool, pub(super) toasts: VecDeque, @@ -843,6 +846,110 @@ impl Game<'_> { } } } +impl Game<'_> { + /// `ClientAdvancements.update` (ClientboundUpdateAdvancementsPacket): + /// the server's advancements replace or join the tree, each changed one + /// takes the progress sent, and one just done shows its toast. `icons` + /// are the added advancements' icon items by name. + pub(super) fn remote_advancements( + &mut self, + p: horizon_protocol::packets::play::UpdateAdvancements, + icons: Vec, + ) { + use horizon_client::scoreboard::tag_to_json; + let mut list: Vec = Vec::new(); + let mut positions: Vec<(f32, f32)> = Vec::new(); + if !p.reset { + let old = self.adv.positions.take().unwrap_or_default(); + for (i, a) in self.adv.tree.list.iter().enumerate() { + if !p.removed.contains(&a.id) { + list.push(a.clone()); + positions.push(old.get(i).copied().unwrap_or((0.0, 0.0))); + } + } + } else { + self.adv.progress = Progress::default(); + } + for id in &p.removed { + self.adv.progress.criteria.remove(id); + } + for (a, icon) in p.added.into_iter().zip(icons) { + list.retain(|o| o.id != a.id); + let display = a.display.map(|d| adv::Display { + icon, + title: tag_to_json(&d.title), + description: tag_to_json(&d.description), + frame: match d.frame { + 1 => Frame::Challenge, + 2 => Frame::Goal, + _ => Frame::Task, + }, + background: d.background, + show_toast: d.show_toast, + announce: false, + hidden: d.hidden, + }); + let mut criteria: Vec = Vec::new(); + for name in a.requirements.iter().flatten() { + if !criteria.iter().any(|c| &c.name == name) { + criteria.push(adv::Criterion { + name: name.clone(), + trigger: String::new(), + conditions: Value::Null, + }); + } + } + list.push(adv::Advancement { + id: a.id, + parent: a.parent, + display, + criteria, + requirements: a.requirements, + rewards: Default::default(), + }); + positions.push((a.x, a.y)); + } + let mut tree = Tree { + list, + ..Tree::default() + }; + for (i, a) in tree.list.iter().enumerate() { + tree.by_id.insert(a.id.clone(), i); + } + self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect(); + self.adv.tree = Arc::new(tree); + self.adv.positions = Some(positions); + let tree = self.adv.tree.clone(); + for (id, criteria) in p.progress { + let Some(&i) = tree.by_id.get(&id) else { + continue; + }; + // The client only shows whether a criterion is obtained, not when. + let obtained: BTreeMap = criteria + .into_iter() + .filter(|(_, at)| at.is_some()) + .map(|(name, _)| (name, String::new())) + .collect(); + self.adv.progress.criteria.insert(id, obtained); + let a = &tree.list[i]; + if !p.reset + && p.show + && self.adv.progress.done(a) + && let Some(d) = a.display.as_ref().filter(|d| d.show_toast) + { + self.adv.toasts.push_back(Toast { + icon: d.icon.clone(), + frame: d.frame, + title: text_of(&d.title), + slide: Slide::default(), + recipes: Vec::new(), + changed: false, + last_changed: 0, + }); + } + } + } +} /// A text component from advancement JSON (`translate` or `text`). pub(super) fn text_of(v: &Value) -> Text { if let Some(key) = v["translate"].as_str() { diff --git a/crates/horizon-client/src/game/advancements_screen.rs b/crates/horizon-client/src/game/advancements_screen.rs index 5e1c0343b..759588887 100644 --- a/crates/horizon-client/src/game/advancements_screen.rs +++ b/crates/horizon-client/src/game/advancements_screen.rs @@ -163,11 +163,18 @@ impl Game<'_> { } let tree = self.adv.tree.clone(); let kids = tree.children(); - let pos = tree - .layout() - .into_iter() - .map(|p| p.map(|(x, y)| (x * 28, (y * 27.0).floor() as i32))) - .collect(); + // A server's advancements come placed (`DisplayInfo` x, y). + let pos = match &self.adv.positions { + Some(server) => server + .iter() + .map(|&(x, y)| Some(((x * 28.0).floor() as i32, (y * 27.0).floor() as i32))) + .collect(), + None => tree + .layout() + .into_iter() + .map(|p| p.map(|(x, y)| (x * 28, (y * 27.0).floor() as i32))) + .collect(), + }; self.adv_ui.cache = Some(Cache { tree, kids, pos }); } fn adv_done(&self, i: usize) -> bool { @@ -184,7 +191,12 @@ impl Game<'_> { }; }; let tree = &c.tree; - let visible = tree.visible(&c.kids, |i| self.adv.progress.done(&tree.list[i])); + // A server sends only what the player may see. + let visible = if self.adv.positions.is_some() { + vec![true; tree.list.len()] + } else { + tree.visible(&c.kids, |i| self.adv.progress.done(&tree.list[i])) + }; // AdvancementTab.create: a displayed root with a background. let mut tabs: Vec = (0..tree.list.len()) .filter(|&i| { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a30f1ce29..59af07ac8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -313,6 +313,9 @@ impl Game<'_> { }); // The level's TickRateManager follows the server's ticking packets. self.clock = horizon_client::clock::FixedStep::client(); + // The player's advancements and statistics are the server's. + self.adv = Default::default(); + self.stats = Default::default(); Ok(()) } @@ -336,6 +339,8 @@ impl Game<'_> { }; horizon_client::crash::clear_detail("Server"); self.clock = Default::default(); + self.adv = Default::default(); + self.stats = Default::default(); self.debug_charts.reset(); self.tab_list.reset(); self.score.board = Default::default(); @@ -1718,6 +1723,46 @@ impl Game<'_> { self.clock.set_frozen(p.frozen); } C::TickingStep(p) => self.clock.set_frozen_ticks_to_run(p.steps), + C::UpdateAdvancements(p) => { + let icons = p + .added + .iter() + .map(|a| { + a.display + .as_ref() + .map_or_else(String::new, |d| self.item_name(d.icon.item).to_string()) + }) + .collect(); + self.remote_advancements(p, icons); + } + // handleAwardStats: StatsCounter.setValue for each. + C::AwardStats(p) => { + let Some(r) = self.remote.as_ref() else { + return Ok(()); + }; + let mut known = Vec::new(); + for (ty, value, count) in p.stats { + let Some(ty) = r + .builtin + .get("minecraft:stat_type") + .and_then(|t| t.name(ty)) + else { + continue; + }; + let values = match ty { + "minecraft:mined" => "minecraft:block", + "minecraft:killed" | "minecraft:killed_by" => "minecraft:entity_type", + "minecraft:custom" => "minecraft:custom_stat", + _ => "minecraft:item", + }; + if let Some(key) = r.builtin.get(values).and_then(|v| v.name(value)) { + known.push((ty.to_owned(), key.to_owned(), count)); + } + } + for (ty, key, count) in known { + self.stats.values.entry(ty).or_default().insert(key, count); + } + } C::SetActionBarText(p) | C::SetTitleText(p) => { let lang = self .remote diff --git a/crates/horizon-client/src/game/stats_screen.rs b/crates/horizon-client/src/game/stats_screen.rs index f023f30b7..40b151453 100644 --- a/crates/horizon-client/src/game/stats_screen.rs +++ b/crates/horizon-client/src/game/stats_screen.rs @@ -173,6 +173,12 @@ const FOOTER: f32 = 33.0; impl Game<'_> { pub(super) fn open_stats(&mut self) { self.load_stats(); + // StatsScreen.init: a server's client asks for its statistics. + if self.remote.is_some() { + self.send(horizon_protocol::packets::play::Serverbound::ClientCommand( + horizon_protocol::packets::play::ClientCommand { action: 1 }, + )); + } self.stats_ui = StatsUi::default(); self.screen = Screen::Stats; } diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 81d429865..90ea5b6cd 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -218,6 +218,42 @@ impl Codec> for Slot { } } +/// ItemStackTemplate.STREAM_CODEC: the item, the count, then the patch. +pub struct Template; +impl Codec for Template { + fn read(r: &mut Reader) -> Result { + let item = r.varint()?; + let count = r.varint()?; + let positive = r.count(65536)?; + let negative = r.count(65536)?; + let mut added = Vec::with_capacity(positive.min(64)); + for _ in 0..positive { + let kind = r.varint()?; + added.push((kind, Component::read(kind, r)?)); + } + let removed = (0..negative).map(|_| r.varint()).collect::>()?; + Ok(Stack { + item, + count, + added, + removed, + }) + } + fn write(s: &Stack, w: &mut Writer) { + w.varint(s.item); + w.varint(s.count); + w.varint(s.added.len() as i32); + w.varint(s.removed.len() as i32); + for (kind, c) in &s.added { + w.varint(*kind); + c.write(*kind, w); + } + for kind in &s.removed { + w.varint(*kind); + } + } +} + /// HashedStack: what the client believes a slot holds. Component values are /// sent as hashes; Horizon sends patches without hashes, so a server whose /// stack carries components resynchronises that slot (as it does for any diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index cecbc098d..47b6d6362 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -982,10 +982,200 @@ impl Codec for Commands { } } +/// `DisplayInfo` of an advancement as sent. +#[derive(Clone, Debug, PartialEq)] +pub struct AdvancementDisplay { + pub title: Tag, + pub description: Tag, + pub icon: crate::item::Stack, + /// `AdvancementType` ordinal: task, challenge, goal. + pub frame: i32, + pub show_toast: bool, + pub hidden: bool, + pub background: Option, +} +/// `ClientboundUpdateAdvancementsPacket.PositionedAdvancement`. +#[derive(Clone, Debug, PartialEq)] +pub struct Advancement { + pub id: String, + pub parent: Option, + pub display: Option, + pub requirements: Vec>, + pub telemetry: bool, + pub x: f32, + pub y: f32, +} +/// `ClientboundUpdateAdvancementsPacket`: whether it replaces what the +/// client has, the advancements added and removed, the progress of each +/// changed one (criterion, when obtained in epoch milliseconds), and whether +/// to show toasts. +#[derive(Clone, Debug, PartialEq)] +pub struct UpdateAdvancements { + pub reset: bool, + pub added: Vec, + pub removed: Vec, + pub progress: Vec<(String, Vec<(String, Option)>)>, + pub show: bool, +} +impl Codec for UpdateAdvancements { + fn read(r: &mut Reader) -> Result { + let reset = r.bool()?; + let n = r.count(r.remaining())?; + let mut added = Vec::with_capacity(n.min(1024)); + for _ in 0..n { + let id = r.string(32767)?; + let parent = if r.bool()? { + Some(r.string(32767)?) + } else { + None + }; + let display = if r.bool()? { + let title = r.nbt()?; + let description = r.nbt()?; + let icon = crate::item::Template::read(r)?; + let frame = r.varint()?; + let flags = r.i32()?; + let background = if flags & 1 != 0 { + Some(r.string(32767)?) + } else { + None + }; + Some(AdvancementDisplay { + title, + description, + icon, + frame, + show_toast: flags & 2 != 0, + hidden: flags & 4 != 0, + background, + }) + } else { + None + }; + let groups = r.count(r.remaining())?; + let mut requirements = Vec::with_capacity(groups.min(256)); + for _ in 0..groups { + let k = r.count(r.remaining())?; + requirements.push((0..k).map(|_| r.string(32767)).collect::>()?); + } + let telemetry = r.bool()?; + let (x, y) = (r.f32()?, r.f32()?); + added.push(Advancement { + id, + parent, + display, + requirements, + telemetry, + x, + y, + }); + } + let n = r.count(r.remaining())?; + let removed = (0..n).map(|_| r.string(32767)).collect::>()?; + let n = r.count(r.remaining())?; + let mut progress = Vec::with_capacity(n.min(1024)); + for _ in 0..n { + let id = r.string(32767)?; + let k = r.count(r.remaining())?; + let mut criteria = Vec::with_capacity(k.min(256)); + for _ in 0..k { + let name = r.string(32767)?; + let at = if r.bool()? { Some(r.i64()?) } else { None }; + criteria.push((name, at)); + } + progress.push((id, criteria)); + } + let show = r.bool()?; + Ok(Self { + reset, + added, + removed, + progress, + show, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.bool(v.reset); + w.varint(v.added.len() as i32); + for a in &v.added { + w.string(&a.id); + w.bool(a.parent.is_some()); + if let Some(p) = &a.parent { + w.string(p); + } + w.bool(a.display.is_some()); + if let Some(d) = &a.display { + w.nbt(&d.title); + w.nbt(&d.description); + crate::item::Template::write(&d.icon, w); + w.varint(d.frame); + w.i32( + i32::from(d.background.is_some()) + | i32::from(d.show_toast) << 1 + | i32::from(d.hidden) << 2, + ); + if let Some(b) = &d.background { + w.string(b); + } + } + w.varint(a.requirements.len() as i32); + for g in &a.requirements { + w.varint(g.len() as i32); + for c in g { + w.string(c); + } + } + w.bool(a.telemetry); + w.f32(a.x); + w.f32(a.y); + } + w.varint(v.removed.len() as i32); + for id in &v.removed { + w.string(id); + } + w.varint(v.progress.len() as i32); + for (id, criteria) in &v.progress { + w.string(id); + w.varint(criteria.len() as i32); + for (name, at) in criteria { + w.string(name); + w.bool(at.is_some()); + if let Some(at) = at { + w.i64(*at); + } + } + } + w.bool(v.show); + } +} +packet!( + /// ClientboundAwardStatsPacket: (stat type, value, count) by network id. + AwardStats { stats: Vec<(i32, i32, i32)> => StatList } +); +/// `Object2IntMap>`: each stat's type and value ids, then its count. +pub struct StatList; +impl Codec> for StatList { + fn read(r: &mut Reader) -> Result> { + let n = r.count(r.remaining())?; + (0..n) + .map(|_| Ok((r.varint()?, r.varint()?, r.varint()?))) + .collect() + } + fn write(v: &Vec<(i32, i32, i32)>, w: &mut Writer) { + w.varint(v.len() as i32); + for &(a, b, c) in v { + w.varint(a); + w.varint(b); + w.varint(c); + } + } +} + packet_enum!(Clientbound, crate::ids::play::clientbound { BundleDelimiter(Empty) = BUNDLE_DELIMITER, AddEntity(AddEntity) = ADD_ENTITY, Animate(Animate) = ANIMATE, + AwardStats(AwardStats) = AWARD_STATS, BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK, BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION, BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA, @@ -1072,6 +1262,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, TickingState(TickingState) = TICKING_STATE, TickingStep(TickingStep) = TICKING_STEP, + UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, }); @@ -1538,6 +1729,35 @@ mod tests { frozen: true, }), Clientbound::TickingStep(TickingStep { steps: 7 }), + Clientbound::AwardStats(AwardStats { + stats: vec![(8, 3, 120), (0, 1, 2)], + }), + Clientbound::UpdateAdvancements(UpdateAdvancements { + reset: true, + added: vec![Advancement { + id: "minecraft:story/root".into(), + parent: None, + display: Some(AdvancementDisplay { + title: literal("Minecraft"), + description: literal("The heart and story of the game"), + icon: crate::item::Stack::new(42, 1), + frame: 0, + show_toast: false, + hidden: false, + background: Some("minecraft:block/stone".into()), + }), + requirements: vec![vec!["crafting_table".into()]], + telemetry: false, + x: 0.0, + y: 1.5, + }], + removed: vec!["minecraft:story/gone".into()], + progress: vec![( + "minecraft:story/root".into(), + vec![("crafting_table".into(), Some(1_792_216_800_000))], + )], + show: true, + }), ]; for p in packets { round_trip(p, Clientbound::encode, Clientbound::decode); From 6c6b58dd55fb068101467887fa3891dbc970ddc8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:23:00 +0200 Subject: [PATCH 026/327] Server: the level follows its lone player through Nether and End portals The server holds one level at a time, as the in-frame game does. While one player is online (single player on the server thread, or a world with one player in it), a Nether or End portal swaps the server's level the in-frame way (switch_level, split out of enter_dimension) and the player is moved as ServerPlayer.teleport moves it into another level: a Respawn packet keeping all data, the difficulty, permission level, teleport, abilities, level info, inventory, effects and the portal travel sound, then a teleport to the exit once the destination has loaded (the Nether portal found or built, the End platform, the Overworld's spawn column). Respawning away from the Overworld takes the level back there first. What the hub sends follows the level: - Chunks carry the level's sections only (y 0 to 255 in the Nether and the End), without sky light where the dimension has none, and heightmaps from the level's floor. Until now every level went out with the Overworld's 24 sections, which a client in the Nether or the End reads 64 blocks off. - The dimension type follows the level the hub names; the default spawn position is the Overworld's. - A level switch keeps the block change log (an open hub kept none after a portal) and the sculk watch list. Worlds whose player is in the Nether or the End now open on the server thread too. The network client maps the End to the End (it drew it as the Overworld) and shows the death screen on its own PlayerCombatKill, as ClientPacketListener.handlePlayerCombatKill does, whatever health came last. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 32 ++- crates/horizon-client/src/game/end.rs | 125 +++++---- crates/horizon-client/src/game/integrated.rs | 16 +- crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 3 +- .../horizon-client/src/game/nether_portal.rs | 33 ++- crates/horizon-client/src/game/remote.rs | 13 +- .../horizon-client/src/game/server_travel.rs | 248 ++++++++++++++++++ crates/horizon-client/src/lan/chunks.rs | 96 +++++-- crates/horizon-client/src/lan/hub.rs | 85 +++++- crates/horizon-client/src/save.rs | 15 +- 11 files changed, 553 insertions(+), 114 deletions(-) create mode 100644 crates/horizon-client/src/game/server_travel.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 73fcbbf52..1c7145b9e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -112,6 +112,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod server_travel; mod shader_packs; mod shield; mod sign_edit; @@ -972,6 +973,8 @@ struct Game<'a> { world_root: PathBuf, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, + /// A server's lone player on its way to another level. + server_trip: Option, /// Nether portals: the player's, items' and mobs' (game/nether_portal.rs). portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). @@ -6434,6 +6437,17 @@ impl Game<'_> { let Some(player) = self.player.take() else { return Ok(()); }; + let from = self.dim; + let destination = self.switch_level(target, player.position)?; + self.trigger_dimension(from, target); + self.travelling = Some((player, destination)); + self.end_travel = (target == Dim::End || from == Dim::End) && self.end_portal_travel; + Ok(()) + } + /// The level swap under a dimension change: save the departing level, + /// open `target`'s, and return where a player leaving from `from` goes + /// (scaled coordinates, or the End portal's fixed destination). + pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result { // Save the departing dimension's changed chunks. self.streaming.save(&mut self.world, true); let keys: Vec<_> = self.world.modified.drain().collect(); @@ -6449,11 +6463,10 @@ impl Game<'_> { _ => 1.0, }; let destination = self.end_destination(target).unwrap_or(Vec3::new( - player.position.x * scale, - player.position.y, - player.position.z * scale, + from.x * scale, + from.y, + from.z * scale, )); - let from_end = self.dim == Dim::End; let (streaming, save) = self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; let mut world = World::new(self.res.facts.air, self.level.seed); @@ -6461,12 +6474,14 @@ impl Game<'_> { world.game_time = self.world.game_time; world.day_time = self.world.day_time; world.weather = self.world.weather; + // An open hub keeps hearing the new level's block changes. + world.block_log = self.world.block_log.as_ref().map(|_| Vec::new()); + // The sculk tables' watched blocks are built once per game. + world.watched = std::mem::take(&mut self.world.watched); self.streaming = streaming; self.world = world; self.save = save; - let from = self.dim; self.dim = target; - self.trigger_dimension(from, target); self.level.dimension = target.id().to_owned(); self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); @@ -6479,13 +6494,11 @@ impl Game<'_> { self.pickups.clear(); self.orbs.clear(); self.mining = None; - self.travelling = Some((player, destination)); - self.end_travel = (target == Dim::End || from_end) && self.end_portal_travel; if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } self.apply_settings(); - Ok(()) + Ok(destination) } /// PortalShape: an obsidian frame around 2..=21 by 3..=21 empty blocks. fn portal_shape(&self, start: [i32; 3], x_axis: bool) -> Option<([i32; 3], i32, i32)> { @@ -10045,6 +10058,7 @@ impl<'a> Game<'a> { dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, + server_trip: None, portals: Default::default(), end_travel: false, respawn_config: None, diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d02904872..a80c51796 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -222,7 +222,7 @@ impl Game<'_> { } } - fn block_name(&self, p: [i32; 3]) -> std::sync::Arc { + pub(super) fn block_name(&self, p: [i32; 3]) -> std::sync::Arc { self.res .facts .get(self.world.block(p[0], p[1], p[2])) @@ -366,31 +366,11 @@ impl Game<'_> { if self.travelling.is_some() || p.health.dead_or_dying() { return Ok(()); } - let w = f64::from(p.dimensions.width) / 2.0; - let lo = [p.position.x - w, p.position.y, p.position.z - w]; - let hi = [ - p.position.x + w, - p.position.y + f64::from(p.dimensions.height), - p.position.z + w, - ]; - let mut portal = false; - let mut gateway = None; - for x in lo[0].floor() as i32..=hi[0].floor() as i32 { - for y in lo[1].floor() as i32..=hi[1].floor() as i32 { - for z in lo[2].floor() as i32..=hi[2].floor() as i32 { - let name = self.block_name([x, y, z]); - // EndPortalBlock entity-inside shape: y 6/16..12/16. - if &*name == "minecraft:end_portal" - && lo[1] < f64::from(y) + 0.75 - && hi[1] > f64::from(y) + 0.375 - { - portal = true; - } else if &*name == "minecraft:end_gateway" && self.dim == Dim::End { - gateway = Some([x, y, z]); - } - } - } - } + let (portal, gateway) = self.inside_end_portals( + p.position, + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); if portal { if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { @@ -417,6 +397,38 @@ impl Game<'_> { Ok(()) } + /// Whether a `width` by `height` box at `position` is inside an End + /// portal (its entity-inside shape), and the End gateway it touches. + pub(super) fn inside_end_portals( + &self, + position: Vec3, + width: f64, + height: f64, + ) -> (bool, Option<[i32; 3]>) { + let w = width / 2.0; + let lo = [position.x - w, position.y, position.z - w]; + let hi = [position.x + w, position.y + height, position.z + w]; + let mut portal = false; + let mut gateway = None; + for x in lo[0].floor() as i32..=hi[0].floor() as i32 { + for y in lo[1].floor() as i32..=hi[1].floor() as i32 { + for z in lo[2].floor() as i32..=hi[2].floor() as i32 { + let name = self.block_name([x, y, z]); + // EndPortalBlock entity-inside shape: y 6/16..12/16. + if &*name == "minecraft:end_portal" + && lo[1] < f64::from(y) + 0.75 + && hi[1] > f64::from(y) + 0.375 + { + portal = true; + } else if &*name == "minecraft:end_gateway" && self.dim == Dim::End { + gateway = Some([x, y, z]); + } + } + } + } + (portal, gateway) + } + /// EndPortalBlock.getPortalDestination for the pending enter_dimension. pub(super) fn end_destination(&self, target: Dim) -> Option { if !self.end_portal_travel { @@ -451,10 +463,36 @@ impl Game<'_> { self.previous_eye = 1.62; self.clock.reset(); } - let mut position = target; - if let Some(job) = self.end.job.take() { - position = self.resolve_gateway(job, target)?; - } else if self.dim == Dim::End { + let position = if let Some(job) = self.end.job.take() { + self.resolve_gateway(job, target)? + } else { + let (position, yaw) = self.end_arrival(target)?; + if let Some(yaw) = yaw { + self.yaw = yaw; + player.yaw = yaw; + player.head_yaw = yaw; + } + position + }; + player.position = position; + player.velocity = Vec3::ZERO; + player.fall_distance = 0.0; + self.previous_position = player.position; + self.player = Some(player); + self.pad.player_replaced(); + self.sway = Default::default(); + self.apply_equipment(); + let pitch = self.world.random.next_float() * 0.4 + 0.8; + self.audio + .play("minecraft:block.portal.travel", None, 0.25, pitch); + Ok(()) + } + + /// Where an End portal's traveller lands once `target` has loaded, and + /// the yaw it faces there: the platform below the End's spawn point, + /// facing west, or the top of the Overworld's spawn column. + pub(super) fn end_arrival(&mut self, target: Vec3) -> Result<(Vec3, Option)> { + if self.dim == Dim::End { // EndPlatformFeature.createEndPlatform below the spawn point. let origin = [END_SPAWN[0], END_SPAWN[1] - 1, END_SPAWN[2]]; for dz in -2..=2 { @@ -473,28 +511,13 @@ impl Game<'_> { } } // Direction.WEST.toYRot(). - self.yaw = 90.0; - player.yaw = 90.0; - player.head_yaw = 90.0; - } else { - // ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column. - let y = self - .land_column(target.x.floor() as i32, target.z.floor() as i32) - .map_or(target.y, f64::from); - position = Vec3::new(target.x, y, target.z); + return Ok((target, Some(90.0))); } - player.position = position; - player.velocity = Vec3::ZERO; - player.fall_distance = 0.0; - self.previous_position = player.position; - self.player = Some(player); - self.pad.player_replaced(); - self.sway = Default::default(); - self.apply_equipment(); - let pitch = self.world.random.next_float() * 0.4 + 0.8; - self.audio - .play("minecraft:block.portal.travel", None, 0.25, pitch); - Ok(()) + // ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column. + let y = self + .land_column(target.x.floor() as i32, target.z.floor() as i32) + .map_or(target.y, f64::from); + Ok((Vec3::new(target.x, y, target.z), None)) } /// Dying away from the Overworld respawns at the world spawn there. diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 1ecdbff28..7b5f3cced 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -8,11 +8,9 @@ //! //! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the //! player joins as a network player, and the server side of a network player -//! does not do everything single player does yet. Worlds whose player is -//! outside the Overworld open the usual way, since network players stay in -//! the Overworld so far. +//! does not do everything single player does yet. use super::{ - Dim, Game, Options, PackResources, Resources, + Game, Options, PackResources, Resources, lan::{LanSettings, Owner}, }; use horizon_client::{ @@ -20,7 +18,6 @@ use horizon_client::{ audio::Audio, hud::HudAtlas, lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig}, - save::Level, settings::Settings, title::WorldOptions, }; @@ -137,12 +134,9 @@ struct Launch { player: String, } -/// Whether this world opens on a server thread: asked for, and its player -/// (if any yet) in the Overworld. -pub(super) fn wanted(options: &Options, world: &Path) -> bool { - options.server_thread - && options.dedicated.is_none() - && Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld) +/// Whether this world opens on a server thread: asked for. +pub(super) fn wanted(options: &Options, _world: &Path) -> bool { + options.server_thread && options.dedicated.is_none() } impl Game<'_> { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 3fc959027..0cc61255d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -851,6 +851,7 @@ impl Game<'_> { } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); + self.tick_server_travel(&mut host); self.lan_swings(&mut host); self.lan_update_streaming(&host); self.lan_update_models(&mut host); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 716bd6ae0..4572fc43c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -846,6 +846,7 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } + self.respawn_level(host); let g = &mut host.hub.guests[i]; g.dead = false; g.health = 20.0; @@ -891,7 +892,7 @@ impl Game<'_> { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; }; - if host.hub.guests[gi].dead { + if host.hub.guests[gi].dead || self.on_server_trip(conn) { continue; } let play = host.play.entry(conn).or_default(); diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 01a657b0b..df684e713 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -92,13 +92,13 @@ impl Game<'_> { } } /// `ServerLevel.isAllowedToEnterPortal`. - fn may_enter(&self, target: Dim) -> bool { + pub(super) fn may_enter(&self, target: Dim) -> bool { target != Dim::Nether || self.ui.rules.bool("allow_entering_nether_using_portals") } /// The plan of an entity of `width` by `height` at `at` going through the /// portal at `entry` (`getDimensionTransitionFromExit` and the scaled, /// clamped exit of `getPortalDestination`). - fn portal_plan( + pub(super) fn portal_plan( &self, entry: BlockPos, at: Vec3, @@ -195,7 +195,7 @@ impl Game<'_> { } /// The exit portal of `plan` in the loaded dimension: the closest one /// within reach, else one built by `PortalForcer.createPortal`. - fn nether_exit_portal(&mut self, plan: &Plan) -> Option { + pub(super) fn nether_exit_portal(&mut self, plan: &Plan) -> Option { let to_nether = plan.dim == Dim::Nether; let radius = if to_nether { 16 } else { 128 }; let border = self.border_bounds(); @@ -231,7 +231,7 @@ impl Game<'_> { } /// `NetherPortalBlock.createDimensionTransition`: the arrival position /// and the yaw turned by. - fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { + pub(super) fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { let b = &self.res.behaviours; let corner = exit.min_corner; let exit_x_axis = b @@ -312,8 +312,16 @@ impl Game<'_> { self.portals.travel = Some(plan); self.end_portal_travel = false; self.enter_dimension(plan.dim)?; - // The destination is all on disk now: load around the portal its - // points of interest lead to, or the approximate exit. + let centre = self.arrival_centre(&plan); + if let Some((_, target)) = self.travelling.as_mut() { + *target = centre; + } + Ok(()) + } + /// Where to wait for the destination of `plan` to load, once its level + /// is open: the portal its points of interest lead to, or the + /// approximate exit. + pub(super) fn arrival_centre(&self, plan: &Plan) -> Vec3 { let to_nether = plan.dim == Dim::Nether; let portals = self.portal_blocks(plan.approximate, if to_nether { 16 } else { 128 }); let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) }; @@ -327,14 +335,11 @@ impl Game<'_> { max_section, ); let centre = found.unwrap_or(plan.approximate); - if let Some((_, target)) = self.travelling.as_mut() { - *target = Vec3::new( - f64::from(centre.x) + 0.5, - f64::from(centre.y), - f64::from(centre.z) + 0.5, - ); - } - Ok(()) + Vec3::new( + f64::from(centre.x) + 0.5, + f64::from(centre.y), + f64::from(centre.z) + 0.5, + ) } /// The player's arrival once the destination has loaded around the /// approximate exit: the waiting entities first, then the exit portal diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 6fc342a96..0e26267fe 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -549,11 +549,7 @@ impl Game<'_> { r.loaded_sent = false; r.predictions.clear(); self.set_mode_id(spawn.game_type); - self.dim = if spawn.dimension == "minecraft:the_nether" { - Dim::Nether - } else { - Dim::Overworld - }; + self.dim = Dim::from_id(&spawn.dimension); if !same { let mut streaming = Streaming::new( Arc::new(NoTerrain), @@ -1246,9 +1242,16 @@ impl Game<'_> { .map(|r| r.lang.clone()) .unwrap_or_default(); let message = plain(&p.message, &lang); + let me = self.remote.as_ref().is_some_and(|r| r.entity_id == p.id); if let Some(r) = self.remote.as_mut() { r.death_message = Some(message); } + // ClientPacketListener.handlePlayerCombatKill: the death + // screen, whatever health was last sent. + if me && self.screen != Screen::Dead && self.player.is_some() { + self.screen = Screen::Dead; + self.capture(false); + } } C::SetExperience(p) => { self.experience = Experience { diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs new file mode 100644 index 000000000..d5b1e4d95 --- /dev/null +++ b/crates/horizon-client/src/game/server_travel.rs @@ -0,0 +1,248 @@ +//! A server's player between dimensions. +//! +//! The server holds one level at a time, as the in-frame game does. While a +//! single player is online (single player on the server thread, or a world +//! with one player in it) that level follows the player through Nether and +//! End portals, and back to the Overworld when the player respawns. The swap +//! is the in-frame path's (`switch_level`, the portal plans, the arrival +//! search); the player hears it as `ServerPlayer.teleport` into another +//! level: a Respawn packet keeping all data, then a teleport to the exit once +//! the destination has loaded. With several players online the portals do +//! not take anyone yet: that needs the server to hold every level. + +use super::nether_portal::PLAYER_DELAY; +use super::{Dim, Game, lan::LanHost}; +use horizon_client::lan::hub::TickCtx; +use horizon_core::{geometry::Vec3, position::BlockPos}; + +/// A trip under way: the level has changed and its chunks are loading +/// around `target`. +pub(super) struct Trip { + conn: u32, + target: Vec3, + /// Through an End portal (or out of the End by respawning). + end: bool, +} + +/// The lone player's box: Player's standing dimensions. +const WIDTH: f64 = 0.6; +const HEIGHT: f64 = 1.8; + +impl Game<'_> { + /// Whether `conn` is between two levels: the server leaves its body + /// alone until it arrives. + pub(super) fn on_server_trip(&self, conn: u32) -> bool { + self.server_trip.as_ref().is_some_and(|t| t.conn == conn) + } + + /// Per server tick, after the guests' own: `Entity.handlePortal` for the + /// lone player (Nether portals count up their transition time, End + /// portals take it at once), or the arrival of the trip under way. + pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) { + if self.options.dedicated.is_none() { + return; + } + if self.server_trip.is_some() { + self.arrive_server_trip(host); + return; + } + let [g] = host.hub.guests.as_slice() else { + return; + }; + if !g.placed || !g.loaded || g.dead || g.spectator() { + return; + } + let (conn, at, invulnerable, sleeping) = ( + g.conn, + Vec3::new(g.position[0], g.position[1], g.position[2]), + g.creative(), + g.sleeping, + ); + // Entity.checkInsideBlocks: the Nether portal blocks the box is in. + if let Some(pos) = self.nether_portal_inside(at) { + self.portals.player.set_inside(pos, PLAYER_DELAY); + } + let (end_portal, _) = self.inside_end_portals(at, WIDTH, HEIGHT); + if end_portal { + if self.portals.player.cooldown == 0 { + let target = if self.dim == Dim::End { + Dim::Overworld + } else { + Dim::End + }; + self.start_server_trip(host, conn, target, true); + } + // Entity.setAsInsidePortal while cooling down restarts the cooldown. + self.portals.player.cooldown = 10; + return; + } + let rule = if invulnerable { + "players_nether_portal_creative_delay" + } else { + "players_nether_portal_default_delay" + }; + let transition = self.ui.rules.int(rule).max(0); + let Some(entry) = self + .portals + .player + .handle(!sleeping, transition, PLAYER_DELAY) + else { + return; + }; + let plan = self.portal_plan(entry, at, WIDTH as f32, HEIGHT as f32, true); + if !self.may_enter(plan.dim) { + return; + } + self.portals.travel = Some(plan); + self.start_server_trip(host, conn, plan.dim, false); + } + + /// A Nether portal block the lone player's box is in. + fn nether_portal_inside(&self, at: Vec3) -> Option { + let w = WIDTH / 2.0 - 1.0e-5; + let lo = [at.x - w, at.y + 1.0e-5, at.z - w]; + let hi = [at.x + w, at.y + HEIGHT - 1.0e-5, at.z + w]; + for x in lo[0].floor() as i32..=hi[0].floor() as i32 { + for y in lo[1].floor() as i32..=hi[1].floor() as i32 { + for z in lo[2].floor() as i32..=hi[2].floor() as i32 { + if &*self.block_name([x, y, z]) == "minecraft:nether_portal" { + return Some(BlockPos::new(x, y, z)); + } + } + } + } + None + } + + /// The level swap, and the player told it is in the new level at the + /// approximate exit while it loads. + fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let g = &host.hub.guests[i]; + let from = Vec3::new(g.position[0], g.position[1], g.position[2]); + let yaw = g.yaw; + let source = self.dim; + self.end_portal_travel = end; + let switched = self.switch_level(target, from); + self.end_portal_travel = false; + let destination = match switched { + Ok(d) => d, + Err(e) => { + log::error!("could not open {}: {e}", target.id()); + return; + } + }; + let destination = match self.portals.travel { + Some(plan) if !end => self.arrival_centre(&plan), + _ => destination, + }; + host.hub.set_dimension(target.id()); + let at = [destination.x, destination.y, destination.z]; + let ctx = self.server_ctx(); + host.hub.change_level(i, at, yaw, &ctx); + self.as_guest(host, conn, |g| g.trigger_dimension(source, target)); + self.server_trip = Some(Trip { + conn, + target: destination, + end, + }); + } + + /// Once the destination has loaded around the trip's target: the exit + /// (the Nether portal found or built, the End platform, the Overworld's + /// spawn column) and the teleport there. + fn arrive_server_trip(&mut self, host: &mut LanHost) { + let Some(trip) = self.server_trip.as_ref() else { + return; + }; + let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { + // They left on the way. + self.server_trip = None; + self.portals.travel = None; + return; + }; + let (cx, cz) = ( + (trip.target.x.floor() as i32) >> 4, + (trip.target.z.floor() as i32) >> 4, + ); + if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return; + } + let Some(trip) = self.server_trip.take() else { + return; + }; + self.resolve_arrivals(); + let (position, yaw) = if trip.end { + match self.end_arrival(trip.target) { + Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)), + Err(e) => { + log::error!("End arrival: {e}"); + (trip.target, host.hub.guests[i].yaw) + } + } + } else { + let plan = self.portals.travel.take(); + let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan)); + match (plan, exit) { + (Some(plan), Some(exit)) => { + let (at, rotation) = self.arrival(&plan, exit); + (at, host.hub.guests[i].yaw + rotation) + } + _ => (trip.target, host.hub.guests[i].yaw), + } + }; + // Player.getDimensionChangingDelay. + self.portals.player.cooldown = 10; + let g = &mut host.hub.guests[i]; + g.yaw = yaw; + // A new body at the exit: no fall distance or motion carried over. + g.motion = None; + host.hub + .teleport(i, Some([position.x, position.y, position.z])); + } + + /// `PlayerList.respawn` away from the Overworld: the lone player's level + /// goes back to the Overworld first, where the world spawn is. + pub(super) fn respawn_level(&mut self, host: &mut LanHost) { + if self.options.dedicated.is_none() || self.dim == Dim::Overworld { + return; + } + if host.hub.guests.len() != 1 { + return; + } + self.server_trip = None; + self.portals.travel = None; + self.end_portal_travel = true; + let from = self.spawn.unwrap_or(Vec3::ZERO); + let switched = self.switch_level(Dim::Overworld, from); + self.end_portal_travel = false; + if let Err(e) = switched { + log::error!("could not open the Overworld: {e}"); + return; + } + host.hub.set_dimension(Dim::Overworld.id()); + } + + /// The hub's view of the server for packets sent outside its own tick. + pub(super) fn server_ctx(&mut self) -> TickCtx<'_> { + let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); + TickCtx { + world: &mut self.world, + host: None, + entities: &[], + next_entity: &mut self.next_entity, + spawn, + difficulty: i32::from(self.ui.difficulty), + difficulty_locked: self.level.difficulty_locked, + clock_rate: if self.ui.rules.bool("advance_time") { + self.ui.clock.rate + } else { + 0.0 + }, + tick_rate: self.clock.rate(), + tick_frozen: self.clock.frozen(), + } + } +} diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 6ca321edd..99b87a20e 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -90,6 +90,11 @@ pub struct ChunkEncoder { pub block_ids: Vec, /// The save's tables, for the heightmaps. pub tables: Option>, + /// The level's sections among a column's: all of them in the Overworld, + /// y 0 to 255 in the Nether and the End (`DimensionType` min_y and height). + sections: std::ops::Range, + /// Whether the level has sky light (`DimensionType.hasSkyLight`). + sky: bool, } impl ChunkEncoder { /// `biome_names`: the internal biome list in order; `biome_registry`: @@ -143,8 +148,20 @@ impl ChunkEncoder { biome_bits: ceil_log2(biome_registry.len()), block_ids, tables: None, + sections: 0..SECTIONS, + sky: true, } } + /// Encode for a level of `min_y` and `height` (multiples of 16 within + /// the column), with or without sky light. + pub fn set_dimension(&mut self, min_y: i32, height: i32, sky: bool) { + let lo = usize::try_from((min_y - MIN_Y) >> 4) + .unwrap_or(0) + .min(SECTIONS); + let n = usize::try_from(height >> 4).unwrap_or(SECTIONS); + self.sections = lo..(lo + n).min(SECTIONS); + self.sky = sky; + } pub fn entity_type(&self, state: u16) -> Option { self.entity_types .get(usize::from(state)) @@ -200,7 +217,7 @@ impl ChunkEncoder { /// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir). fn occupied(&self, chunk: &Chunk) -> u64 { let mut bits = 0u64; - for (i, s) in chunk.sections.iter().enumerate() { + for (i, s) in chunk.sections[self.sections.clone()].iter().enumerate() { let mut unpacked = [0u16; BLOCKS]; s.unpack(&mut unpacked); let any = unpacked @@ -225,7 +242,7 @@ impl ChunkEncoder { } } let mut packet = self.encode(chunk, &world.block_entities); - packet.light = light_data(chunk, around); + packet.light = self.light(chunk, around); packet } @@ -234,9 +251,15 @@ impl ChunkEncoder { chunk: &Chunk, block_entities: &HashMap<(i32, i32, i32), BlockEntity>, ) -> LevelChunkWithLight { - let mut sections = Vec::with_capacity(SECTIONS); + let mut sections = Vec::with_capacity(self.sections.len()); let mut entity_infos = Vec::new(); - for (i, s) in chunk.sections.iter().enumerate() { + for (i, s) in chunk + .sections + .iter() + .enumerate() + .skip(self.sections.start) + .take(self.sections.len()) + { let (encoded, has_entities) = self.section(s); if has_entities { for y in 0..16 { @@ -293,14 +316,30 @@ impl ChunkEncoder { heightmaps: self .tables .as_ref() - .map(|t| crate::save::client_heightmaps(chunk, t)) + .map(|t| { + let min_y = MIN_Y + 16 * self.sections.start as i32; + let height = 16 * self.sections.len() as i32; + crate::save::client_heightmaps_in(chunk, t, min_y, height) + }) .unwrap_or_default(), buffer: ChunkData::from_sections(§ions), block_entities: entity_infos, }, - light: light_data(chunk, u64::MAX), + light: self.light(chunk, u64::MAX), } } + + /// The light layers of the level's sections. + fn light(&self, chunk: &Chunk, around: u64) -> LightData { + let mut data = light_data(&chunk.sections[self.sections.clone()], around); + if !self.sky { + // No sky light storage at all. + data.sky_mask.clear(); + data.empty_sky_mask.clear(); + data.sky.clear(); + } + data + } } /// The order LevelChunk.getBlockEntities() iterates in: a fastutil @@ -373,7 +412,8 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { /// non-air section of this column or a neighbouring one (`around`, bit i for /// section i; LayerLightSectionStorage.updateSectionStatus). An existing /// layer is sent, or marked empty when all dark; the others are left out. -fn light_data(chunk: &Chunk, around: u64) -> LightData { +fn light_data(sections: &[Arc
], around: u64) -> LightData { + let n = sections.len(); let mut data = LightData { sky_mask: Vec::new(), block_mask: Vec::new(), @@ -383,19 +423,18 @@ fn light_data(chunk: &Chunk, around: u64) -> LightData { block: Vec::new(), }; // Light section b holds chunk section b - 1. - let exists = |b: usize| { - (b.saturating_sub(2)..=b.min(SECTIONS - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0) - }; + let exists = + |b: usize| (b.saturating_sub(2)..=b.min(n - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0); let full_sky = Light::Uniform(0xF0); - for b in 0..SECTIONS + 2 { + for b in 0..n + 2 { if !exists(b) { continue; } let light = match b { // Below the world nothing is lit; above it the sky is full. 0 => &Light::Uniform(0), - _ if b == SECTIONS + 1 => &full_sky, - _ => &chunk.sections[b - 1].light, + _ if b == n + 1 => &full_sky, + _ => §ions[b - 1].light, }; let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]); let (mut sky_any, mut block_any) = (false, false); @@ -464,12 +503,39 @@ mod tests { fn light_masks_cover_the_world_plus_borders() { let chunk = Chunk::empty(0, 0); // A column with nothing around it has no light layers at all. - assert!(light_data(&chunk, 0).sky.is_empty()); - let data = light_data(&chunk, u64::MAX); + assert!(light_data(&chunk.sections, 0).sky.is_empty()); + let data = light_data(&chunk.sections, u64::MAX); // Default sections are full sky light and no block light. assert_eq!(data.sky.len(), SECTIONS + 1); assert_eq!(data.block.len(), 0); assert_eq!(data.sky[0][0], 0xFF); assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5)); } + + #[test] + fn a_nether_column_sends_its_sixteen_sections_without_sky_light() { + let chunk = Chunk::empty(0, 0); + let mut encoder = ChunkEncoder::new( + [("minecraft:air".into(), false)], + &Builtin::default(), + &[], + &[], + ); + let overworld = encoder.encode(&chunk, &HashMap::new()); + encoder.set_dimension(0, 256, false); + let nether = encoder.encode(&chunk, &HashMap::new()); + // An all-air section is the same bytes wherever it is. + let per_section = overworld.chunk.buffer.len() / SECTIONS; + assert_eq!(nether.chunk.buffer.len(), per_section * 16); + assert!(nether.light.sky.is_empty() && nether.light.sky_mask.is_empty()); + // Block light layers: one below and one above the sixteen sections. + assert!(horizon_protocol::buf::bit( + &nether.light.empty_block_mask, + 17 + )); + assert!(!horizon_protocol::buf::bit( + &nether.light.empty_block_mask, + 18 + )); + } } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 806c91fc3..d98df083e 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -186,9 +186,12 @@ impl Hub { .id("minecraft:chat_type", "minecraft:chat") .unwrap_or(0); let dimension_type = sync - .id("minecraft:dimension_type", "minecraft:overworld") + .id("minecraft:dimension_type", &config.dimension) .unwrap_or(0); let clock_ids = (0..sync.dynamic.len("minecraft:world_clock") as i32).collect(); + let mut encoder = encoder; + let d = horizon_protocol::registry::DimensionType::vanilla(&config.dimension); + encoder.set_dimension(d.min_y, d.height, d.has_skylight); Self { lan, config, @@ -737,11 +740,12 @@ impl Hub { })); } - /// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data. + /// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data + /// (the world spawn, in the Overworld wherever the player is). fn default_spawn(&self, spawn: [f64; 3]) -> C { C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition { pos: play::GlobalPos { - dimension: self.config.dimension.clone(), + dimension: "minecraft:overworld".into(), pos: [ spawn[0].floor() as i32, spawn[1].floor() as i32, @@ -1831,6 +1835,81 @@ impl Hub { // ServerPlayer.initInventoryMenu. self.send_inventory(i); } + + /// The level the players are in: the server holds one at a time, and the + /// hub's packets name it. + pub fn set_dimension(&mut self, dimension: &str) { + self.config.dimension = dimension.to_owned(); + self.dimension_type = self + .sync + .id("minecraft:dimension_type", dimension) + .unwrap_or(0); + let d = horizon_protocol::registry::DimensionType::vanilla(dimension); + self.encoder + .set_dimension(d.min_y, d.height, d.has_skylight); + } + + /// ServerPlayer.teleport(TeleportTransition) into the level the hub now + /// names (`set_dimension`): ClientboundRespawnPacket keeping all data, + /// then vanilla's packet order. Nothing tracked in the old level is + /// removed one by one: the client drops its whole level. + pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) { + let mode = self.guests[i].game_mode; + let info = self.spawn_info(mode); + self.close_container_for(i); + let g = &mut self.guests[i]; + g.tracker.clear(); + g.sent_chunks.clear(); + g.chunk_queue.clear(); + g.center = None; + g.yaw = yaw; + g.position = at; + g.previous_position = at; + g.send(&C::Respawn(play::Respawn { + spawn: info, + // ClientboundRespawnPacket.KEEP_ALL_DATA. + keep: 3, + })); + g.send(&C::ChangeDifficulty(play::ChangeDifficulty { + difficulty: ctx.difficulty, + locked: ctx.difficulty_locked, + })); + self.send_permission_level(i); + self.teleport(i, None); + let g = &mut self.guests[i]; + g.send(&C::PlayerAbilities(play::PlayerAbilities { + flags: g.ability_flags(), + flying_speed: 0.05, + walking_speed: 0.1, + })); + self.send_level_info(i, ctx); + // PlayerList.sendAllPlayerInfo: the inventory and the held slot. + self.send_inventory(i); + let g = &mut self.guests[i]; + g.send(&C::SetHeldSlot(play::SetHeldSlot { + slot: g.selected as i32, + })); + self.send_active_effects(i); + let g = &mut self.guests[i]; + // ServerPlayer.sendPostEffects. + g.send(&raw(ids::POST_EFFECTS, vec![0])); + // TeleportTransition.PLAY_PORTAL_SOUND. + g.send(&C::LevelEvent(play::LevelEvent { + kind: 1032, + pos: [0, 0, 0], + data: 0, + global: false, + })); + // lastSentExp, lastSentHealth and lastSentFood. + g.sent_health = None; + g.sent_xp = None; + let (cx, cz) = g.chunk(); + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + g.center_sent = Some((cx, cz)); + } } /// A packet Horizon sends as raw bytes (no fields worth a type). diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index a8553e276..398a340a2 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -730,6 +730,15 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { /// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES), /// as (network id, packed longs) in Heightmap.Types order. pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec)> { + client_heightmaps_in(chunk, tables, MIN_Y, SECTIONS as i32 * 16) +} +/// The client heightmaps of a level from `min_y`, `height` blocks high. +pub fn client_heightmaps_in( + chunk: &Chunk, + tables: &SaveTables, + min_y: i32, + height: i32, +) -> Vec<(i32, Vec)> { let kinds = [ (1, HeightmapType::WorldSurface), (4, HeightmapType::MotionBlocking), @@ -737,11 +746,7 @@ pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec = kinds .iter() - .filter_map(|(id, k)| { - Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16) - .ok() - .map(|m| (*id, m)) - }) + .filter_map(|(id, k)| Heightmap::new(*k, min_y, height).ok().map(|m| (*id, m))) .collect(); let view = HeightmapView { chunk, tables }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect(); From edffb857e116389b399822def3a768d997b15221 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:56:06 +0200 Subject: [PATCH 027/327] LAN chunks: compute a column's light once, and keep sections' light layers encode_in built the light layers twice (encode filled them for every section, then encode_in replaced them with the ones that exist around the column). On the ThinkPad at 25 walking bots light_data was 8 % of the server thread. The light is now built once, and a section's packed DataLayers stay in the section cache while the section is unchanged (relighting moves it to a new address, as an edit does). Uniform light is filled directly, not kept. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/chunks.rs | 148 ++++++++++++++++++------ 1 file changed, 115 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 71e0c889b..32d38efe9 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -112,6 +112,47 @@ struct Encoded { non_air: bool, /// LevelChunkSection.write, and whether it holds block entity blocks. wire: Option<(Arc<[u8]>, bool)>, + /// The section's light as the wire's two DataLayers, when not uniform. + light: Option>, +} + +/// One section's light as DataLayers (two blocks per byte, the even one in +/// the low nibble), and whether each holds any light. +struct Layers { + sky: Vec, + block: Vec, + sky_any: bool, + block_any: bool, +} +impl Layers { + fn of(light: &Light) -> Self { + let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]); + let (sky_any, block_any) = match light { + Light::Uniform(v) => { + let (sk, bl) = (v >> 4, v & 15); + sky.fill(sk | sk << 4); + block.fill(bl | bl << 4); + (sk != 0, bl != 0) + } + Light::Full(a) => { + for ((pair, sky), block) in + a.as_chunks::<2>().0.iter().zip(&mut sky).zip(&mut block) + { + let [even, odd] = *pair; + *sky = even >> 4 | (odd & 0xF0); + *block = (even & 15) | odd << 4; + } + let all = a.iter().fold(0u8, |acc, &v| acc | v); + (all & 0xF0 != 0, all & 15 != 0) + } + }; + Self { + sky, + block, + sky_any, + block_any, + } + } } /// Sections kept before the ones no longer resident are dropped. @@ -221,6 +262,7 @@ impl ChunkEncoder { section: Arc::downgrade(section), non_air: self.non_air(section), wire: None, + light: None, }); read(entry) } @@ -338,8 +380,8 @@ impl ChunkEncoder { } } } - let mut packet = self.encode(chunk, &world.block_entities); - packet.light = light_data(chunk, around); + let mut packet = self.encode_blocks(chunk, &world.block_entities); + packet.light = self.light_data(chunk, around); packet } @@ -347,6 +389,17 @@ impl ChunkEncoder { &self, chunk: &Chunk, block_entities: &HashMap<(i32, i32, i32), BlockEntity>, + ) -> LevelChunkWithLight { + let mut packet = self.encode_blocks(chunk, block_entities); + packet.light = self.light_data(chunk, u64::MAX); + packet + } + + /// The packet without its light. + fn encode_blocks( + &self, + chunk: &Chunk, + block_entities: &HashMap<(i32, i32, i32), BlockEntity>, ) -> LevelChunkWithLight { let mut buffer = Vec::new(); let mut entity_infos = Vec::new(); @@ -412,9 +465,34 @@ impl ChunkEncoder { buffer, block_entities: entity_infos, }, - light: light_data(chunk, u64::MAX), + light: LightData { + sky_mask: Vec::new(), + block_mask: Vec::new(), + empty_sky_mask: Vec::new(), + empty_block_mask: Vec::new(), + sky: Vec::new(), + block: Vec::new(), + }, } } + + /// ClientboundLightUpdatePacketData: the light layers of the sections + /// that exist around the column (`around`: the non-air sections of it + /// and its neighbours, as bits). A resident section's layers come from + /// the cache while it is unchanged (uniform light is quicker to fill than + /// to keep). + fn light_data(&self, chunk: &Chunk, around: u64) -> LightData { + light_data_with(chunk, around, |s| { + if matches!(s.light, Light::Uniform(_)) { + return Arc::new(Layers::of(&s.light)); + } + self.cached(s, |e| e.light.clone()).unwrap_or_else(|| { + let layers = Arc::new(Layers::of(&s.light)); + self.cached(s, |e| e.light = Some(layers.clone())); + layers + }) + }) + } } /// The order LevelChunk.getBlockEntities() iterates in: a fastutil @@ -487,7 +565,17 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { /// non-air section of this column or a neighbouring one (`around`, bit i for /// section i; LayerLightSectionStorage.updateSectionStatus). An existing /// layer is sent, or marked empty when all dark; the others are left out. +#[cfg(test)] fn light_data(chunk: &Chunk, around: u64) -> LightData { + light_data_with(chunk, around, |s| Arc::new(Layers::of(&s.light))) +} + +/// The light layers, `section` giving a resident section's. +fn light_data_with( + chunk: &Chunk, + around: u64, + section: impl Fn(&Arc
) -> Arc, +) -> LightData { let mut data = LightData { sky_mask: Vec::new(), block_mask: Vec::new(), @@ -500,47 +588,25 @@ fn light_data(chunk: &Chunk, around: u64) -> LightData { let exists = |b: usize| { (b.saturating_sub(2)..=b.min(SECTIONS - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0) }; - let full_sky = Light::Uniform(0xF0); for b in 0..SECTIONS + 2 { if !exists(b) { continue; } - let light = match b { + let layers = match b { // Below the world nothing is lit; above it the sky is full. - 0 => &Light::Uniform(0), - _ if b == SECTIONS + 1 => &full_sky, - _ => &chunk.sections[b - 1].light, + 0 => Arc::new(Layers::of(&Light::Uniform(0))), + _ if b == SECTIONS + 1 => Arc::new(Layers::of(&Light::Uniform(0xF0))), + _ => section(&chunk.sections[b - 1]), }; - let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]); - let (sky_any, block_any) = match light { - Light::Uniform(v) => { - let (sk, bl) = (v >> 4, v & 15); - sky.fill(sk | sk << 4); - block.fill(bl | bl << 4); - (sk != 0, bl != 0) - } - Light::Full(a) => { - // Two blocks per byte, the even one in the low nibble. - for ((pair, sky), block) in - a.as_chunks::<2>().0.iter().zip(&mut sky).zip(&mut block) - { - let [even, odd] = *pair; - *sky = even >> 4 | (odd & 0xF0); - *block = (even & 15) | odd << 4; - } - let all = a.iter().fold(0u8, |acc, &v| acc | v); - (all & 0xF0 != 0, all & 15 != 0) - } - }; - if sky_any { + if layers.sky_any { set_bit(&mut data.sky_mask, b); - data.sky.push(sky); + data.sky.push(layers.sky.clone()); } else { set_bit(&mut data.empty_sky_mask, b); } - if block_any { + if layers.block_any { set_bit(&mut data.block_mask, b); - data.block.push(block); + data.block.push(layers.block.clone()); } else { set_bit(&mut data.empty_block_mask, b); } @@ -629,6 +695,22 @@ mod tests { } } + #[test] + fn cached_light_follows_edits() { + let encoder = encoder(); + let mut chunk = Chunk::empty(0, 0); + let mut light = Box::new([0x5Au8; 4096]); + Arc::make_mut(&mut chunk.sections[2]).light = Light::Full(light.clone()); + let first = encoder.encode(&chunk, &HashMap::new()).light; + assert_eq!(first, light_data(&chunk, u64::MAX)); + // Relighting moves the section, so the cached layers aren't reused. + light[7] = 0xF3; + Arc::make_mut(&mut chunk.sections[2]).light = Light::Full(light); + let second = encoder.encode(&chunk, &HashMap::new()).light; + assert_ne!(first, second); + assert_eq!(second, light_data(&chunk, u64::MAX)); + } + #[test] fn light_masks_cover_the_world_plus_borders() { let chunk = Chunk::empty(0, 0); From 6b0b34098eaa855e3526a87192031f662479689a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 08:09:50 +0200 Subject: [PATCH 028/327] Benchmark: Horizon's server against vanilla 26.3 on equal work Walk and explore passes at 1 to 100 bots on the ThinkPad (bots on the Mac mini), vanilla with the locator bar off, plus an explore pass at a rate both servers keep up with. The README has the method, the tables, the profile of what remains at 25 walking bots and the earlier runs; docs/server.md section 9 and the Scale row summarise it. Co-Authored-By: Claude Opus 5.5 --- .../server-equal-work-2026-10-17/README.md | 168 +++++ .../explore-equal-rate.json | 267 +++++++ .../server-equal-work-2026-10-17/horizon.json | 415 +++++++++++ .../run-1-before-chunk-cache.json | 693 ++++++++++++++++++ .../run-2-chunk-cache.json | 413 +++++++++++ .../server-equal-work-2026-10-17/vanilla.json | 324 ++++++++ docs/server.md | 20 +- 7 files changed, 2297 insertions(+), 3 deletions(-) create mode 100644 benchmarks/server-equal-work-2026-10-17/README.md create mode 100644 benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json create mode 100644 benchmarks/server-equal-work-2026-10-17/horizon.json create mode 100644 benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json create mode 100644 benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json create mode 100644 benchmarks/server-equal-work-2026-10-17/vanilla.json diff --git a/benchmarks/server-equal-work-2026-10-17/README.md b/benchmarks/server-equal-work-2026-10-17/README.md new file mode 100644 index 000000000..737b05858 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/README.md @@ -0,0 +1,168 @@ +# Horizon's server against vanilla 26.3, equal work (2026-10-17) + +The same bots on Horizon's dedicated server and on vanilla 26.3's, one server at a time, on the same +machine, with the work each server does made the same before the numbers are compared. This replaces the +first run in docs/server.md section 9, where the work wasn't equal. + +## What was made equal + +The first run (PR #556) had three differences that made the comparison unfair. Each is fixed in the code +that ran here: + +- **Refused moves.** Vanilla pulls a player back when a move is too fast ("moved too quickly") or ends + inside a block ("moved wrongly"). Horizon now runs both checks the way vanilla does (PR #586), so a bot + that flies too fast is pulled back on both servers. +- **Chunk sending.** Vanilla paces chunks by the client's acknowledgements (PlayerChunkSender: one + unacknowledged batch at first, then ten, each at most the client's desired chunks per tick). Horizon used + to send twice as many per batch; it now paces them the same way (PR #586), and the bots acknowledge + batches and ask for a rate the way vanilla's client does, so both servers send at the pace the client + asks for. Chunks sent again while the bot still held + them (`resent`) are counted: 0 on both servers in every run. +- **Movement gated on chunks.** A bot doesn't move while the chunk it stands in hasn't arrived (vanilla's + client waits the same way), so a slower server isn't asked to teleport bots into terrain it hasn't sent. + +One difference isn't in Horizon yet: vanilla 26.3's locator bar (waypoints), which costs vanilla O(players²) +work per move. Every vanilla run here sets `gamerule locator_bar false`, so neither server does it. + +## Method + +`tools/server_bench.py` runs each configuration on a fresh server: + +- the same `server.properties` on both (seed 12345, view and simulation distance 10, offline, creative, + difficulty easy, `sync-chunk-writes=true`), and `gamerule respawn_radius 0`; +- the server waits for `Done`, the bots join one a second, a 60-second warm-up, then 300 seconds of + measurement; +- MSPT (average, P50, P95, P99) comes from each server's own `/tick query`, asked every 5 seconds on the + console, so both measure themselves the same way (vanilla's ServerTickRateManager numbers, which Horizon + reproduces); TPS is 20 while the average fits in 50 ms, else 1000 / MSPT; +- RSS and CPU are the server's whole process tree, once a second (100 % is one core); +- chunk counts come from the bots: chunks received per second, chunks no bot had before (new terrain), and + pull-backs (position packets that move a bot back). + +The bots are `horizon-bots` (creative, flying 24 blocks above spawn, 20 moves a second): + +- `walk`: flies to random points within 48 blocks of spawn at sprint speed (5.6 blocks a second); +- `explore`: flies straight outwards, by default at about 22 blocks a second, as fast as the server sends + chunks. + +Machine: the ThinkPad (Intel Core i7-7500U, 2 cores / 4 threads, 32 GB, NixOS), servers under `nice -n 19` +because it also runs other services; vanilla on OpenJDK 25.0.4.1 with a 4 GB heap (`-Xms4g -Xmx4g`). The +bots ran on the Mac mini and reached the ThinkPad over the tailnet, so they took none of the server's CPU. + +What ran: Horizon from `origin/main` at bf851bfe with #586 (move checks and chunk pacing), the bots and +`server_bench.py` from this PR, #623 (sections encoded once, its first commit) and #649 (a tick's packets +handed to each connection together). The ThinkPad copy wasn't a git checkout, so the JSON reports have an +empty `commit`. Vanilla: the pinned 26.3 server jar. + +## Results + +MSPT is the average milliseconds per tick (50 is the limit for 20 TPS); P95 is the 95th percentile. CPU is +the whole process tree. "New chunks/s" are chunks no bot had before. + +### Walk (the same work on both servers) + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 5.5 | 12.1 | 20.0 | 1.37 GB | 57 % | 9 | 0.3 | +| 1 | Vanilla | 18.3 | 27.3 | 20.0 | 3.35 GB | 66 % | 10 | 0.3 | +| 10 | Horizon | 11.5 | 22.1 | 20.0 | 1.41 GB | 124 % | 94 | 2.4 | +| 10 | Vanilla | 16.8 | 30.5 | 20.0 | 3.41 GB | 84 % | 100 | 2.8 | +| 25 | Horizon | 20.7 | 40.4 | 20.0 | 1.45 GB | 170 % | 236 | 5.7 | +| 25 | Vanilla | 16.0 | 26.4 | 20.0 | 3.47 GB | 115 % | 252 | 6.7 | +| 50 | Horizon | 31.4 | 79.0 | 20.0 | 1.52 GB | 173 % | 451 | 10.3 | +| 50 | Vanilla | 20.5 | 29.7 | 20.0 | 3.55 GB | 194 % | 502 | 12.2 | +| 100 | Horizon | 114.5 | 256.2 | 8.7 | 1.33 GB | 181 % | 484 | 30.8 | +| 100 | Vanilla | stopped by its watchdog | | | | | | | + +Both servers sent the same chunks (about 10 a second per bot, the churn of flying around) and sent none +twice. Vanilla pulled back a few bots for moving too quickly when a tick ran long (5 to 33 per run); +Horizon none. At 100 bots vanilla's watchdog stopped the server (a tick ran over 60 s, in +`ChunkMap$TrackedEntity.updatePlayer`); Horizon kept running at 8.7 TPS. + +### Explore at a rate both servers keep up with (equal work) + +The bots fly outwards at 0.8 blocks a second (`--explore-speed 0.8`), slow enough that neither server makes +them wait for terrain, so both generate and send the same new chunks. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 4.0 | 6.6 | 20.0 | 1.36 GB | 25 % | 2 | 1.3 | +| 1 | Vanilla | 18.1 | 27.1 | 20.0 | 3.32 GB | 73 % | 2 | 1.4 | +| 10 | Horizon | 13.5 | 24.8 | 20.0 | 1.64 GB | 89 % | 13 | 11.8 | +| 10 | Vanilla | 29.2 | 43.0 | 20.0 | 3.52 GB | 143 % | 13 | 11.9 | +| 25 | Horizon | 20.2 | 36.8 | 20.0 | 1.74 GB | 121 % | 32 | 28.9 | +| 25 | Vanilla | 37.0 | 49.4 | 20.0 | 3.73 GB | 169 % | 32 | 28.9 | + +### Explore as fast as each server sends chunks (not equal work) + +The default 22 blocks a second is faster than either server can generate, so each server sets the pace and +a faster server is given more work: from 10 bots Horizon generated 1.5 to 2 times vanilla's new chunks a +second. Read it as throughput, not as a like-for-like tick time. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 10.6 | 24.6 | 20.0 | 1.34 GB | 322 % | 39 | 34.6 | +| 1 | Vanilla | 9.9 | 21.3 | 20.0 | 3.48 GB | 245 % | 36 | 33.4 | +| 10 | Horizon | 30.4 | 52.3 | 20.0 | 2.18 GB | 345 % | 47 | 46.7 | +| 10 | Vanilla | 17.0 | 29.6 | 20.0 | 4.04 GB | 242 % | 22 | 22.4 | +| 25 | Horizon | 50.7 | 89.3 | 19.7 | 2.30 GB | 286 % | 50 | 49.7 | +| 25 | Vanilla | 24.2 | 36.5 | 20.0 | 4.40 GB | 320 % | 34 | 33.7 | +| 50 | Horizon | 50.7 | 102.7 | 19.7 | 1.72 GB | 213 % | 97 | 96.5 | +| 50 | Vanilla | stopped by its watchdog | | | | | | | +| 100 | Horizon | 92.9 | 139.6 | 10.8 | 1.70 GB | 322 % | 114 | 113.6 | +| 100 | Vanilla | stopped by its watchdog | | | | | | | + +Vanilla's watchdog stopped it at 50 bots (in `ClientboundLightUpdatePacketData`, copying light for a chunk +packet) and at 100 (in `Entity.move` from a move packet). + +## Findings + +- Horizon's RSS is 1.9 to 2.6 times smaller in every run, and it starts in 11 s against vanilla's 15 s. + Vanilla's heap is fixed at 4 GB (`-Xms4g`), so part of its RSS is that setting rather than need. +- With 1 bot Horizon's tick is 3.3 times shorter walking and 4.5 times shorter exploring at equal work; + at 10 bots it is still shorter in both. +- At equal exploring work Horizon's tick is about half of vanilla's at 10 and 25 bots. +- When the bots only fly around spawn (`walk`), vanilla's tick hardly grows with players (16 to 20 ms from + 1 to 50 bots) while Horizon's grows by about 0.5 ms per bot, so vanilla is ahead from about 20 bots: 16.0 + against 20.7 ms at 25 and 20.5 against 31.4 ms at 50. Both keep 20 TPS up to 50. +- With 100 bots vanilla's watchdog stops it in every pass, and Horizon keeps running at 9 to 11 TPS. + +### Where Horizon's walk tick goes at 25 bots + +Profiled on the ThinkPad with `perf` (the server thread, 20 s, self time): + +| Share | What | Whose | +|---:|---|---| +| 18 % | `Streaming::update`: every tick it walks all loaded columns and proto chunks and tests each against every player's area (unloading, dropping protos, finishing and decoration candidates), so the cost grows with players times chunks | streaming / engine tick | +| 20 % | `PalettedContainer::get` and `World::block`, mostly from block entity ticks: on the Mac profile `tick_hoppers` looks up the block under every block entity in the loaded world each tick and compares names as strings, and spawners rebuild their display id | engine tick | +| 8 % | `light_data` when a chunk is sent: the light layers were built twice per chunk; a follow-up commit on #623 builds them once and keeps each section's packed layers | server (this work) | +| 7 % | encoding chunk sections and heightmaps for the chunks each bot newly sees | server | +| 4 % | `Hub::tick` (moves, tracking) | server | +| 2 % | the moved-wrongly collision check | server | + +The first two grow with the number of players but aren't specific to the server: they are the +engine's tick and streaming, reported to perf-server-2. Before #623 and #649, encoding every chunk section +once per player and waking each connection's writer thread once per packet cost more than everything above +(at 50 walking bots the tick was 281 ms; see the earlier runs). + +## Earlier runs (same machine and method) + +- `run-1-before-chunk-cache.json`: before #623, with vanilla's locator bar on. Horizon's walk tick was + 27.5, 40.7, 281 and 467 ms at 10, 25, 50 and 100 bots, and vanilla's 33.2 ms at 50 (the locator bar). +- `run-2-chunk-cache.json`: Horizon with #623 only: 13.2, 23.5, 31.4 and 84.4 ms walking at 10 to 100 + bots. + +## Files + +- `horizon.json`, `vanilla.json`: the walk and explore passes (vanilla with `locator_bar=false`). +- `explore-equal-rate.json`: the explore pass at 0.8 blocks a second, both servers. +- `run-1-before-chunk-cache.json`, `run-2-chunk-cache.json`: the earlier runs. + +To run it again (bots on another machine reached at `--connect`): + + cargo build --release -p horizon-client --bin horizon-client -p horizon-server -p horizon-bots + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50,100 --behaviour walk,explore \ + --gamerule locator_bar=false --nice 19 --bots-via 'ssh macmini' --bots-bin /path/to/horizon-bots \ + --connect --out results.json + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --behaviour explore \ + --explore-speed 0.8 --gamerule locator_bar=false --nice 19 ... --out explore-equal-rate.json diff --git a/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json b/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json new file mode 100644 index 000000000..bd097e43a --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json @@ -0,0 +1,267 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T05:47:12+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench5.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 10.91, + "mspt": { + "average": 4.02, + "p50": 3.75, + "p95": 6.63, + "p99": 14.55 + }, + "mspt_worst_p99": 63.3, + "tps": 20.0, + "rss_mb": { + "mean": 1392.42, + "max": 1746.1 + }, + "cpu_percent": 24.52, + "chunks_per_second": 1.69, + "unique_per_second": 1.34, + "forgotten_per_second": 1.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 1048, + "chunks_per_bot": { + "explore": 1048.0 + }, + "unique_chunks_per_bot": { + "explore": 952.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.13, + "mspt": { + "average": 18.12, + "p50": 18.78, + "p95": 27.07, + "p99": 60.81 + }, + "mspt_worst_p99": 1397.6, + "tps": 20.0, + "rss_mb": { + "mean": 3397.31, + "max": 3430.2 + }, + "cpu_percent": 72.99, + "chunks_per_second": 1.69, + "unique_per_second": 1.38, + "forgotten_per_second": 1.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 1048, + "chunks_per_bot": { + "explore": 1048.0 + }, + "unique_chunks_per_bot": { + "explore": 952.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 13.49, + "p50": 12.09, + "p95": 24.81, + "p99": 40.9 + }, + "mspt_worst_p99": 101.4, + "tps": 20.0, + "rss_mb": { + "mean": 1684.04, + "max": 2660.6 + }, + "cpu_percent": 89.04, + "chunks_per_second": 13.08, + "unique_per_second": 11.84, + "forgotten_per_second": 13.02, + "waited_ticks_per_second": 0.0, + "chunks_total": 9277, + "chunks_per_bot": { + "explore": 927.7 + }, + "unique_chunks_per_bot": { + "explore": 889.9 + }, + "resent": 0, + "pulled_back": 3381, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 14.84, + "mspt": { + "average": 29.18, + "p50": 26.76, + "p95": 43.02, + "p99": 80.16 + }, + "mspt_worst_p99": 425.5, + "tps": 20.0, + "rss_mb": { + "mean": 3609.51, + "max": 3791.6 + }, + "cpu_percent": 142.79, + "chunks_per_second": 13.1, + "unique_per_second": 11.88, + "forgotten_per_second": 13.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 9245, + "chunks_per_bot": { + "explore": 924.5 + }, + "unique_chunks_per_bot": { + "explore": 885.3 + }, + "resent": 0, + "pulled_back": 3388, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 20.25, + "p50": 18.73, + "p95": 36.78, + "p99": 55.76 + }, + "mspt_worst_p99": 92.3, + "tps": 20.0, + "rss_mb": { + "mean": 1782.26, + "max": 2741.9 + }, + "cpu_percent": 120.8, + "chunks_per_second": 32.22, + "unique_per_second": 28.89, + "forgotten_per_second": 32.19, + "waited_ticks_per_second": 0.0, + "chunks_total": 23357, + "chunks_per_bot": { + "explore": 934.28 + }, + "unique_chunks_per_bot": { + "explore": 890.32 + }, + "resent": 0, + "pulled_back": 11580, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.54, + "mspt": { + "average": 37.04, + "p50": 34.77, + "p95": 49.42, + "p99": 101.67 + }, + "mspt_worst_p99": 735.2, + "tps": 20.0, + "rss_mb": { + "mean": 3815.46, + "max": 4202.0 + }, + "cpu_percent": 169.15, + "chunks_per_second": 32.34, + "unique_per_second": 28.93, + "forgotten_per_second": 32.31, + "waited_ticks_per_second": 0.0, + "chunks_total": 23306, + "chunks_per_bot": { + "explore": 932.24 + }, + "unique_chunks_per_bot": { + "explore": 886.96 + }, + "resent": 0, + "pulled_back": 11539, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/horizon.json b/benchmarks/server-equal-work-2026-10-17/horizon.json new file mode 100644 index 000000000..d0b162c44 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/horizon.json @@ -0,0 +1,415 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T05:04:57+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench4.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 5.45, + "p50": 4.63, + "p95": 12.14, + "p99": 30.63 + }, + "mspt_worst_p99": 91.5, + "tps": 20.0, + "rss_mb": { + "mean": 1398.5, + "max": 1708.4 + }, + "cpu_percent": 57.03, + "chunks_per_second": 9.17, + "unique_per_second": 0.26, + "forgotten_per_second": 9.2, + "waited_ticks_per_second": 0.0, + "chunks_total": 3708, + "chunks_per_bot": { + "walk": 3708.0 + }, + "unique_chunks_per_bot": { + "walk": 694.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 11.51, + "p50": 10.6, + "p95": 22.13, + "p99": 36.92 + }, + "mspt_worst_p99": 71.9, + "tps": 20.0, + "rss_mb": { + "mean": 1440.2, + "max": 1832.4 + }, + "cpu_percent": 124.19, + "chunks_per_second": 94.04, + "unique_per_second": 2.38, + "forgotten_per_second": 93.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 37269, + "chunks_per_bot": { + "walk": 3726.9 + }, + "unique_chunks_per_bot": { + "walk": 688.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 10.91, + "mspt": { + "average": 20.74, + "p50": 19.27, + "p95": 40.42, + "p99": 57.12 + }, + "mspt_worst_p99": 102.0, + "tps": 20.0, + "rss_mb": { + "mean": 1485.4, + "max": 1871.9 + }, + "cpu_percent": 169.52, + "chunks_per_second": 235.81, + "unique_per_second": 5.68, + "forgotten_per_second": 235.83, + "waited_ticks_per_second": 0.0, + "chunks_total": 94456, + "chunks_per_bot": { + "walk": 3778.24 + }, + "unique_chunks_per_bot": { + "walk": 692.96 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 31.41, + "p50": 25.39, + "p95": 78.97, + "p99": 110.73 + }, + "mspt_worst_p99": 192.9, + "tps": 20.0, + "rss_mb": { + "mean": 1558.34, + "max": 1915.3 + }, + "cpu_percent": 173.27, + "chunks_per_second": 450.85, + "unique_per_second": 10.3, + "forgotten_per_second": 451.86, + "waited_ticks_per_second": 0.0, + "chunks_total": 186885, + "chunks_per_bot": { + "walk": 3737.7 + }, + "unique_chunks_per_bot": { + "walk": 688.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 18.16, + "mspt": { + "average": 114.55, + "p50": 101.37, + "p95": 256.19, + "p99": 338.64 + }, + "mspt_worst_p99": 442.6, + "tps": 8.73, + "rss_mb": { + "mean": 1357.65, + "max": 1358.4 + }, + "cpu_percent": 181.21, + "chunks_per_second": 484.16, + "unique_per_second": 30.76, + "forgotten_per_second": 478.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 212947, + "chunks_per_bot": { + "walk": 2129.47 + }, + "unique_chunks_per_bot": { + "walk": 583.02 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 17.45, + "mspt": { + "average": 10.62, + "p50": 9.2, + "p95": 24.61, + "p99": 38.18 + }, + "mspt_worst_p99": 81.1, + "tps": 20.0, + "rss_mb": { + "mean": 1372.73, + "max": 1568.7 + }, + "cpu_percent": 322.38, + "chunks_per_second": 39.21, + "unique_per_second": 34.6, + "forgotten_per_second": 38.55, + "waited_ticks_per_second": 0.51, + "chunks_total": 12549, + "chunks_per_bot": { + "explore": 12549.0 + }, + "unique_chunks_per_bot": { + "explore": 11168.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.32, + "mspt": { + "average": 30.38, + "p50": 27.84, + "p95": 52.31, + "p99": 77.89 + }, + "mspt_worst_p99": 158.3, + "tps": 20.0, + "rss_mb": { + "mean": 2231.56, + "max": 4022.6 + }, + "cpu_percent": 344.99, + "chunks_per_second": 47.34, + "unique_per_second": 46.73, + "forgotten_per_second": 44.57, + "waited_ticks_per_second": 112.27, + "chunks_total": 19870, + "chunks_per_bot": { + "explore": 1987.0 + }, + "unique_chunks_per_bot": { + "explore": 1966.5 + }, + "resent": 0, + "pulled_back": 16130, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.42, + "mspt": { + "average": 50.67, + "p50": 47.61, + "p95": 89.3, + "p99": 119.15 + }, + "mspt_worst_p99": 222.3, + "tps": 19.73, + "rss_mb": { + "mean": 2358.4, + "max": 4273.7 + }, + "cpu_percent": 286.32, + "chunks_per_second": 50.39, + "unique_per_second": 49.67, + "forgotten_per_second": 47.45, + "waited_ticks_per_second": 311.85, + "chunks_total": 28954, + "chunks_per_bot": { + "explore": 1158.16 + }, + "unique_chunks_per_bot": { + "explore": 1147.56 + }, + "resent": 0, + "pulled_back": 36319, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 20.06, + "mspt": { + "average": 50.69, + "p50": 47.48, + "p95": 102.67, + "p99": 133.27 + }, + "mspt_worst_p99": 274.4, + "tps": 19.73, + "rss_mb": { + "mean": 1764.01, + "max": 2542.0 + }, + "cpu_percent": 212.83, + "chunks_per_second": 97.33, + "unique_per_second": 96.47, + "forgotten_per_second": 76.74, + "waited_ticks_per_second": 750.49, + "chunks_total": 38538, + "chunks_per_bot": { + "explore": 770.76 + }, + "unique_chunks_per_bot": { + "explore": 763.84 + }, + "resent": 0, + "pulled_back": 39880, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 11.82, + "mspt": { + "average": 92.93, + "p50": 87.84, + "p95": 139.6, + "p99": 178.38 + }, + "mspt_worst_p99": 272.9, + "tps": 10.76, + "rss_mb": { + "mean": 1736.38, + "max": 1855.7 + }, + "cpu_percent": 321.53, + "chunks_per_second": 113.89, + "unique_per_second": 113.56, + "forgotten_per_second": 101.68, + "waited_ticks_per_second": 1179.4, + "chunks_total": 84617, + "chunks_per_bot": { + "explore": 846.17 + }, + "unique_chunks_per_bot": { + "explore": 845.01 + }, + "resent": 0, + "pulled_back": 128104, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json b/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json new file mode 100644 index 000000000..d79b3f179 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json @@ -0,0 +1,693 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T00:37:35+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 7.63, + "p50": 5.51, + "p95": 17.46, + "p99": 36.79 + }, + "mspt_worst_p99": 79.6, + "tps": 20.0, + "rss_mb": { + "mean": 1391.94, + "max": 1700.7 + }, + "cpu_percent": 60.18, + "chunks_per_second": 9.15, + "unique_per_second": 0.29, + "forgotten_per_second": 9.18, + "waited_ticks_per_second": 0.0, + "chunks_total": 3682, + "chunks_per_bot": { + "walk": 3682.0 + }, + "unique_chunks_per_bot": { + "walk": 692.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.35, + "mspt": { + "average": 18.08, + "p50": 18.66, + "p95": 28.05, + "p99": 46.94 + }, + "mspt_worst_p99": 456.4, + "tps": 20.0, + "rss_mb": { + "mean": 3455.72, + "max": 3471.7 + }, + "cpu_percent": 65.67, + "chunks_per_second": 9.89, + "unique_per_second": 0.29, + "forgotten_per_second": 9.92, + "waited_ticks_per_second": 0.0, + "chunks_total": 3827, + "chunks_per_bot": { + "walk": 3827.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 11.22, + "mspt": { + "average": 27.53, + "p50": 24.93, + "p95": 53.93, + "p99": 77.03 + }, + "mspt_worst_p99": 111.4, + "tps": 20.0, + "rss_mb": { + "mean": 1433.85, + "max": 1831.9 + }, + "cpu_percent": 138.65, + "chunks_per_second": 95.98, + "unique_per_second": 2.38, + "forgotten_per_second": 95.78, + "waited_ticks_per_second": 0.0, + "chunks_total": 38041, + "chunks_per_bot": { + "walk": 3804.1 + }, + "unique_chunks_per_bot": { + "walk": 690.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.83, + "mspt": { + "average": 18.92, + "p50": 16.02, + "p95": 39.0, + "p99": 56.13 + }, + "mspt_worst_p99": 180.3, + "tps": 20.0, + "rss_mb": { + "mean": 3479.45, + "max": 3535.7 + }, + "cpu_percent": 99.39, + "chunks_per_second": 99.93, + "unique_per_second": 2.94, + "forgotten_per_second": 100.04, + "waited_ticks_per_second": 0.0, + "chunks_total": 38411, + "chunks_per_bot": { + "walk": 3841.1 + }, + "unique_chunks_per_bot": { + "walk": 697.1 + }, + "resent": 0, + "pulled_back": 7, + "moved_too_quickly": 7, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 11.52, + "mspt": { + "average": 40.69, + "p50": 37.28, + "p95": 81.16, + "p99": 108.42 + }, + "mspt_worst_p99": 149.9, + "tps": 20.0, + "rss_mb": { + "mean": 1444.12, + "max": 1882.6 + }, + "cpu_percent": 176.94, + "chunks_per_second": 244.11, + "unique_per_second": 6.51, + "forgotten_per_second": 243.96, + "waited_ticks_per_second": 0.0, + "chunks_total": 95219, + "chunks_per_bot": { + "walk": 3808.76 + }, + "unique_chunks_per_bot": { + "walk": 695.64 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 15.23, + "mspt": { + "average": 18.81, + "p50": 17.26, + "p95": 30.16, + "p99": 53.9 + }, + "mspt_worst_p99": 390.0, + "tps": 20.0, + "rss_mb": { + "mean": 3517.36, + "max": 3555.7 + }, + "cpu_percent": 148.52, + "chunks_per_second": 252.34, + "unique_per_second": 7.75, + "forgotten_per_second": 251.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 96645, + "chunks_per_bot": { + "walk": 3865.8 + }, + "unique_chunks_per_bot": { + "walk": 698.4 + }, + "resent": 0, + "pulled_back": 11, + "moved_too_quickly": 11, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 12.72, + "mspt": { + "average": 281.42, + "p50": 278.28, + "p95": 343.64, + "p99": 384.23 + }, + "mspt_worst_p99": 475.1, + "tps": 3.55, + "rss_mb": { + "mean": 1334.32, + "max": 1335.4 + }, + "cpu_percent": 197.11, + "chunks_per_second": 391.5, + "unique_per_second": 21.24, + "forgotten_per_second": 388.33, + "waited_ticks_per_second": 0.0, + "chunks_total": 153136, + "chunks_per_bot": { + "walk": 3062.72 + }, + "unique_chunks_per_bot": { + "walk": 661.82 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 15.74, + "mspt": { + "average": 33.21, + "p50": 29.9, + "p95": 53.37, + "p99": 109.14 + }, + "mspt_worst_p99": 833.3, + "tps": 20.0, + "rss_mb": { + "mean": 3568.07, + "max": 3594.9 + }, + "cpu_percent": 266.59, + "chunks_per_second": 496.3, + "unique_per_second": 18.64, + "forgotten_per_second": 495.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 191965, + "chunks_per_bot": { + "walk": 3839.3 + }, + "unique_chunks_per_bot": { + "walk": 696.22 + }, + "resent": 0, + "pulled_back": 184, + "moved_too_quickly": 183, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 11.22, + "mspt": { + "average": 467.37, + "p50": 464.62, + "p95": 524.07, + "p99": 548.77 + }, + "mspt_worst_p99": 581.1, + "tps": 2.14, + "rss_mb": { + "mean": 1353.68, + "max": 1354.9 + }, + "cpu_percent": 191.96, + "chunks_per_second": 377.62, + "unique_per_second": 55.8, + "forgotten_per_second": 348.88, + "waited_ticks_per_second": 0.0, + "chunks_total": 165719, + "chunks_per_bot": { + "walk": 1657.19 + }, + "unique_chunks_per_bot": { + "walk": 549.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 56 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 14.84, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 17.07, + "p50": 16.6, + "p95": 32.82, + "p99": 50.3 + }, + "mspt_worst_p99": 113.9, + "tps": 20.0, + "rss_mb": { + "mean": 1391.72, + "max": 1566.6 + }, + "cpu_percent": 333.8, + "chunks_per_second": 39.42, + "unique_per_second": 34.77, + "forgotten_per_second": 39.34, + "waited_ticks_per_second": 0.0, + "chunks_total": 13860, + "chunks_per_bot": { + "explore": 13860.0 + }, + "unique_chunks_per_bot": { + "explore": 12379.0 + }, + "resent": 0, + "pulled_back": 192, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 16.03, + "mspt": { + "average": 9.9, + "p50": 8.04, + "p95": 20.41, + "p99": 63.62 + }, + "mspt_worst_p99": 351.1, + "tps": 20.0, + "rss_mb": { + "mean": 3709.92, + "max": 3776.2 + }, + "cpu_percent": 246.64, + "chunks_per_second": 36.06, + "unique_per_second": 33.33, + "forgotten_per_second": 35.73, + "waited_ticks_per_second": 0.0, + "chunks_total": 12369, + "chunks_per_bot": { + "explore": 12369.0 + }, + "unique_chunks_per_bot": { + "explore": 11559.0 + }, + "resent": 0, + "pulled_back": 222, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.42, + "mspt": { + "average": 33.72, + "p50": 31.08, + "p95": 61.07, + "p99": 89.09 + }, + "mspt_worst_p99": 142.6, + "tps": 20.0, + "rss_mb": { + "mean": 2239.97, + "max": 4108.8 + }, + "cpu_percent": 350.83, + "chunks_per_second": 46.49, + "unique_per_second": 46.08, + "forgotten_per_second": 44.33, + "waited_ticks_per_second": 111.28, + "chunks_total": 19915, + "chunks_per_bot": { + "explore": 1991.5 + }, + "unique_chunks_per_bot": { + "explore": 1974.4 + }, + "resent": 0, + "pulled_back": 17516, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.15, + "mspt": { + "average": 16.25, + "p50": 13.67, + "p95": 28.92, + "p99": 115.9 + }, + "mspt_worst_p99": 1202.1, + "tps": 20.0, + "rss_mb": { + "mean": 4202.72, + "max": 4502.7 + }, + "cpu_percent": 247.47, + "chunks_per_second": 22.3, + "unique_per_second": 22.25, + "forgotten_per_second": 22.64, + "waited_ticks_per_second": 78.89, + "chunks_total": 10092, + "chunks_per_bot": { + "explore": 1009.2 + }, + "unique_chunks_per_bot": { + "explore": 1007.4 + }, + "resent": 0, + "pulled_back": 16286, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.82, + "mspt": { + "average": 48.03, + "p50": 44.99, + "p95": 83.06, + "p99": 109.63 + }, + "mspt_worst_p99": 191.8, + "tps": 20.0, + "rss_mb": { + "mean": 2214.16, + "max": 4598.6 + }, + "cpu_percent": 356.03, + "chunks_per_second": 64.2, + "unique_per_second": 63.5, + "forgotten_per_second": 60.9, + "waited_ticks_per_second": 301.65, + "chunks_total": 32247, + "chunks_per_bot": { + "explore": 1289.88 + }, + "unique_chunks_per_bot": { + "explore": 1279.4 + }, + "resent": 0, + "pulled_back": 42159, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.73, + "mspt": { + "average": 25.73, + "p50": 22.75, + "p95": 37.72, + "p99": 201.98 + }, + "mspt_worst_p99": 4051.5, + "tps": 20.0, + "rss_mb": { + "mean": 4355.9, + "max": 4983.2 + }, + "cpu_percent": 309.3, + "chunks_per_second": 33.33, + "unique_per_second": 33.21, + "forgotten_per_second": 34.22, + "waited_ticks_per_second": 258.68, + "chunks_total": 19426, + "chunks_per_bot": { + "explore": 777.04 + }, + "unique_chunks_per_bot": { + "explore": 772.92 + }, + "resent": 0, + "pulled_back": 53918, + "moved_too_quickly": 93, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 11.01, + "mspt": { + "average": 108.61, + "p50": 107.37, + "p95": 151.96, + "p99": 177.41 + }, + "mspt_worst_p99": 271.6, + "tps": 9.21, + "rss_mb": { + "mean": 1775.98, + "max": 1956.9 + }, + "cpu_percent": 359.7, + "chunks_per_second": 100.32, + "unique_per_second": 98.91, + "forgotten_per_second": 95.42, + "waited_ticks_per_second": 518.15, + "chunks_total": 55956, + "chunks_per_bot": { + "explore": 1119.12 + }, + "unique_chunks_per_bot": { + "explore": 1111.42 + }, + "resent": 0, + "pulled_back": 69967, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.74, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 244.43, + "p50": 243.58, + "p95": 308.39, + "p99": 360.12 + }, + "mspt_worst_p99": 470.2, + "tps": 4.09, + "rss_mb": { + "mean": 1806.85, + "max": 2084.5 + }, + "cpu_percent": 310.46, + "chunks_per_second": 186.87, + "unique_per_second": 182.99, + "forgotten_per_second": 161.75, + "waited_ticks_per_second": 1131.65, + "chunks_total": 100389, + "chunks_per_bot": { + "explore": 1003.89 + }, + "unique_chunks_per_bot": { + "explore": 991.9 + }, + "resent": 0, + "pulled_back": 56791, + "moved_too_quickly": 344, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 14.83, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json b/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json new file mode 100644 index 000000000..4c182395c --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json @@ -0,0 +1,413 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T02:22:59+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench2.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 5.41, + "p50": 4.63, + "p95": 11.61, + "p99": 30.5 + }, + "mspt_worst_p99": 64.6, + "tps": 20.0, + "rss_mb": { + "mean": 1398.84, + "max": 1708.5 + }, + "cpu_percent": 56.84, + "chunks_per_second": 9.19, + "unique_per_second": 0.27, + "forgotten_per_second": 9.22, + "waited_ticks_per_second": 0.0, + "chunks_total": 3713, + "chunks_per_bot": { + "walk": 3713.0 + }, + "unique_chunks_per_bot": { + "walk": 694.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 10.92, + "mspt": { + "average": 13.18, + "p50": 11.74, + "p95": 26.5, + "p99": 44.82 + }, + "mspt_worst_p99": 87.6, + "tps": 20.0, + "rss_mb": { + "mean": 1439.83, + "max": 1831.6 + }, + "cpu_percent": 132.94, + "chunks_per_second": 93.87, + "unique_per_second": 2.38, + "forgotten_per_second": 93.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 37240, + "chunks_per_bot": { + "walk": 3724.0 + }, + "unique_chunks_per_bot": { + "walk": 688.7 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 10.92, + "mspt": { + "average": 23.52, + "p50": 21.92, + "p95": 44.7, + "p99": 63.12 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 1485.82, + "max": 1872.0 + }, + "cpu_percent": 173.82, + "chunks_per_second": 235.63, + "unique_per_second": 5.64, + "forgotten_per_second": 235.72, + "waited_ticks_per_second": 0.0, + "chunks_total": 94549, + "chunks_per_bot": { + "walk": 3781.96 + }, + "unique_chunks_per_bot": { + "walk": 692.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 10.91, + "mspt": { + "average": 31.36, + "p50": 26.08, + "p95": 70.6, + "p99": 92.83 + }, + "mspt_worst_p99": 125.5, + "tps": 20.0, + "rss_mb": { + "mean": 1556.81, + "max": 1913.0 + }, + "cpu_percent": 192.16, + "chunks_per_second": 468.69, + "unique_per_second": 10.43, + "forgotten_per_second": 468.78, + "waited_ticks_per_second": 0.0, + "chunks_total": 193547, + "chunks_per_bot": { + "walk": 3870.94 + }, + "unique_chunks_per_bot": { + "walk": 692.84 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 84.38, + "p50": 81.5, + "p95": 132.92, + "p99": 168.38 + }, + "mspt_worst_p99": 245.5, + "tps": 11.85, + "rss_mb": { + "mean": 1395.64, + "max": 1941.3 + }, + "cpu_percent": 271.28, + "chunks_per_second": 850.05, + "unique_per_second": 21.79, + "forgotten_per_second": 851.1, + "waited_ticks_per_second": 0.0, + "chunks_total": 368464, + "chunks_per_bot": { + "walk": 3684.64 + }, + "unique_chunks_per_bot": { + "walk": 680.58 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 11.63, + "p50": 10.27, + "p95": 24.52, + "p99": 40.53 + }, + "mspt_worst_p99": 99.9, + "tps": 20.0, + "rss_mb": { + "mean": 1413.81, + "max": 1596.1 + }, + "cpu_percent": 329.84, + "chunks_per_second": 39.47, + "unique_per_second": 34.81, + "forgotten_per_second": 39.42, + "waited_ticks_per_second": 0.0, + "chunks_total": 13798, + "chunks_per_bot": { + "explore": 13798.0 + }, + "unique_chunks_per_bot": { + "explore": 12330.0 + }, + "resent": 0, + "pulled_back": 185, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 28.49, + "p50": 26.2, + "p95": 48.58, + "p99": 72.04 + }, + "mspt_worst_p99": 125.7, + "tps": 20.0, + "rss_mb": { + "mean": 2231.06, + "max": 4077.8 + }, + "cpu_percent": 344.95, + "chunks_per_second": 46.31, + "unique_per_second": 45.88, + "forgotten_per_second": 44.14, + "waited_ticks_per_second": 111.95, + "chunks_total": 19722, + "chunks_per_bot": { + "explore": 1972.2 + }, + "unique_chunks_per_bot": { + "explore": 1957.0 + }, + "resent": 0, + "pulled_back": 18533, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 40.04, + "p50": 37.61, + "p95": 62.39, + "p99": 83.64 + }, + "mspt_worst_p99": 147.0, + "tps": 20.0, + "rss_mb": { + "mean": 2466.85, + "max": 4504.5 + }, + "cpu_percent": 340.13, + "chunks_per_second": 60.61, + "unique_per_second": 59.62, + "forgotten_per_second": 56.28, + "waited_ticks_per_second": 299.57, + "chunks_total": 32877, + "chunks_per_bot": { + "explore": 1315.08 + }, + "unique_chunks_per_bot": { + "explore": 1300.72 + }, + "resent": 0, + "pulled_back": 46272, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 11.32, + "mspt": { + "average": 61.82, + "p50": 59.21, + "p95": 90.46, + "p99": 115.58 + }, + "mspt_worst_p99": 320.9, + "tps": 16.18, + "rss_mb": { + "mean": 2634.54, + "max": 4883.1 + }, + "cpu_percent": 356.96, + "chunks_per_second": 95.26, + "unique_per_second": 94.31, + "forgotten_per_second": 85.86, + "waited_ticks_per_second": 528.08, + "chunks_total": 59251, + "chunks_per_bot": { + "explore": 1185.02 + }, + "unique_chunks_per_bot": { + "explore": 1173.96 + }, + "resent": 0, + "pulled_back": 99493, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 10.81, + "mspt": { + "average": 103.24, + "p50": 100.03, + "p95": 144.77, + "p99": 178.8 + }, + "mspt_worst_p99": 258.6, + "tps": 9.69, + "rss_mb": { + "mean": 1784.48, + "max": 1922.0 + }, + "cpu_percent": 336.94, + "chunks_per_second": 115.06, + "unique_per_second": 114.86, + "forgotten_per_second": 109.43, + "waited_ticks_per_second": 1127.57, + "chunks_total": 93839, + "chunks_per_bot": { + "explore": 938.39 + }, + "unique_chunks_per_bot": { + "explore": 935.28 + }, + "resent": 0, + "pulled_back": 133404, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/vanilla.json b/benchmarks/server-equal-work-2026-10-17/vanilla.json new file mode 100644 index 000000000..014554cee --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/vanilla.json @@ -0,0 +1,324 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T03:29:30+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench3.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.43, + "mspt": { + "average": 18.32, + "p50": 19.26, + "p95": 27.34, + "p99": 45.48 + }, + "mspt_worst_p99": 393.3, + "tps": 20.0, + "rss_mb": { + "mean": 3428.43, + "max": 3437.7 + }, + "cpu_percent": 66.47, + "chunks_per_second": 9.92, + "unique_per_second": 0.29, + "forgotten_per_second": 9.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 3850, + "chunks_per_bot": { + "walk": 3850.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.76, + "mspt": { + "average": 16.8, + "p50": 14.55, + "p95": 30.52, + "p99": 50.01 + }, + "mspt_worst_p99": 205.2, + "tps": 20.0, + "rss_mb": { + "mean": 3490.15, + "max": 3580.7 + }, + "cpu_percent": 83.7, + "chunks_per_second": 100.01, + "unique_per_second": 2.83, + "forgotten_per_second": 100.04, + "waited_ticks_per_second": 0.0, + "chunks_total": 38623, + "chunks_per_bot": { + "walk": 3862.3 + }, + "unique_chunks_per_bot": { + "walk": 697.2 + }, + "resent": 0, + "pulled_back": 5, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.84, + "mspt": { + "average": 16.01, + "p50": 14.55, + "p95": 26.39, + "p99": 51.26 + }, + "mspt_worst_p99": 397.8, + "tps": 20.0, + "rss_mb": { + "mean": 3550.02, + "max": 3593.5 + }, + "cpu_percent": 114.96, + "chunks_per_second": 251.62, + "unique_per_second": 6.72, + "forgotten_per_second": 251.16, + "waited_ticks_per_second": 0.0, + "chunks_total": 98701, + "chunks_per_bot": { + "walk": 3948.04 + }, + "unique_chunks_per_bot": { + "walk": 698.84 + }, + "resent": 0, + "pulled_back": 10, + "moved_too_quickly": 10, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 14.43, + "mspt": { + "average": 20.52, + "p50": 19.55, + "p95": 29.72, + "p99": 49.04 + }, + "mspt_worst_p99": 600.4, + "tps": 20.0, + "rss_mb": { + "mean": 3633.12, + "max": 3658.7 + }, + "cpu_percent": 193.84, + "chunks_per_second": 501.86, + "unique_per_second": 12.15, + "forgotten_per_second": 501.8, + "waited_ticks_per_second": 0.0, + "chunks_total": 203429, + "chunks_per_bot": { + "walk": 4068.58 + }, + "unique_chunks_per_bot": { + "walk": 698.66 + }, + "resent": 0, + "pulled_back": 33, + "moved_too_quickly": 32, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.34, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.55, + "mspt": { + "average": 9.93, + "p50": 8.12, + "p95": 21.33, + "p99": 60.19 + }, + "mspt_worst_p99": 373.0, + "tps": 20.0, + "rss_mb": { + "mean": 3564.11, + "max": 3655.0 + }, + "cpu_percent": 245.18, + "chunks_per_second": 35.93, + "unique_per_second": 33.35, + "forgotten_per_second": 35.64, + "waited_ticks_per_second": 0.0, + "chunks_total": 12340, + "chunks_per_bot": { + "explore": 12340.0 + }, + "unique_chunks_per_bot": { + "explore": 11569.0 + }, + "resent": 0, + "pulled_back": 261, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.03, + "mspt": { + "average": 16.99, + "p50": 14.46, + "p95": 29.61, + "p99": 132.18 + }, + "mspt_worst_p99": 1244.0, + "tps": 20.0, + "rss_mb": { + "mean": 4135.2, + "max": 4453.1 + }, + "cpu_percent": 242.32, + "chunks_per_second": 22.39, + "unique_per_second": 22.41, + "forgotten_per_second": 22.78, + "waited_ticks_per_second": 78.78, + "chunks_total": 10177, + "chunks_per_bot": { + "explore": 1017.7 + }, + "unique_chunks_per_bot": { + "explore": 1016.2 + }, + "resent": 0, + "pulled_back": 17314, + "moved_too_quickly": 19, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.84, + "mspt": { + "average": 24.19, + "p50": 21.22, + "p95": 36.51, + "p99": 174.82 + }, + "mspt_worst_p99": 1532.8, + "tps": 20.0, + "rss_mb": { + "mean": 4504.55, + "max": 4988.9 + }, + "cpu_percent": 319.55, + "chunks_per_second": 33.78, + "unique_per_second": 33.66, + "forgotten_per_second": 34.64, + "waited_ticks_per_second": 269.22, + "chunks_total": 20522, + "chunks_per_bot": { + "explore": 820.88 + }, + "unique_chunks_per_bot": { + "explore": 815.76 + }, + "resent": 0, + "pulled_back": 46246, + "moved_too_quickly": 28, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.73, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 14.54, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/docs/server.md b/docs/server.md index 6e165f534..39b790535 100644 --- a/docs/server.md +++ b/docs/server.md @@ -84,7 +84,7 @@ not tick cost, so it is in scope here (see section 9). | Management | Only stdin. There is no service, no backups, no status beyond `list`, no restart after a crash, and a server can't be managed while it runs in the background. | | Packaging | The server is the full game client. Resources come from `horizon-prepare`, which needs a JDK and the official launcher's client install, both awkward on a headless VPS. | | Tick times | The dedicated loop never recorded its tick times in the game clock (only the windowed loop did), so `/tick query` on a dedicated server reported 0 ms. Fixed in PR 2b, which the benchmark needs (section 9). | -| Scale | Not measured with more than one player. The tick is single-threaded, and each remote player costs the hub one tracking and chunk-sending pass. | +| Scale | Measured against vanilla on equal work (section 9, `benchmarks/server-equal-work-2026-10-17/`): 20 TPS up to 50 bots, 9 to 11 TPS at 100, where vanilla's watchdog stops it. Horizon is ahead with few players and when exploring; with 25 to 50 players near spawn vanilla's tick is shorter. | ### Harnesses on main @@ -457,8 +457,22 @@ reproducible by anyone, and show the same gameplay on both sides. - Vanilla's chunk sending yields under load. - Horizon sent each nearby `walk` bot 1.5–4 times as many chunks. - Horizon sent 2–4 times the chunks per second in every multi-bot run. The next run equalises the work - (slower `explore`, a `walk`-only pass) on a quiet machine before anything is published. + Horizon sent 2–4 times the chunks per second in every multi-bot run. +- **Equal-work run (2026-10-17,** `benchmarks/server-equal-work-2026-10-17/`, on the ThinkPad with the bots + on the Mac mini). Horizon now checks moves and paces chunks as vanilla does (#586), the bots wait for the + chunk they stand in, an `--explore-speed` pass keeps both servers at the same rate, and vanilla runs with + `gamerule locator_bar false` (Horizon has no locator bar yet). Results: + - Memory: Horizon's RSS is 1.9 to 2.6 times smaller in every run (vanilla's heap is fixed at 4 GB). + - Walking near spawn: Horizon's tick is shorter with 1 and 10 bots (5.5 against 18.3 ms, 11.5 against + 16.8), and longer with 25 and 50 (20.7 against 16.0, 31.4 against 20.5). Both keep 20 TPS up to 50. + - Exploring at the same rate: Horizon's tick is about half of vanilla's (13.5 against 29.2 ms at 10 bots, + 20.2 against 37.0 at 25). + - At 100 bots: vanilla's watchdog stops it in every pass; Horizon runs at 9 to 11 TPS. + + Two server costs were found and fixed on the way: every chunk section was encoded once per player (#623), + and every packet woke its connection's writer thread (#649). Together they took the 50-bot walking tick + from 281 ms to 31 ms. At 25 walking bots most of what remains is the engine's streaming and block entity + ticks, both of which grow with players (the README has the profile). - **Ownership.** perf-server-1 owns making the tick faster. This work only measures it, files what it finds, and fixes startup, RAM and packaging. From c7ad9b861fea6746cba412b1cf532c8e834edc33 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 08:45:23 +0200 Subject: [PATCH 029/327] Swimming pose and stroke on the player model The player's model never read the swimming pose: sprint-swimming and crawling drew it upright and walking. Add LivingEntity.swimAmount (eased 0.09 a tick toward isVisuallySwimming), AvatarRenderer's swim rotation (tipped by the pitch in water, -90 out of it, laid along the swimming box) and HumanoidModel.setupSwimAnimation (the 26-unit arm stroke, head down, flutter kick). The avatar rotations now follow LivingEntityRenderer.setupRotations' death and upside-down turns, as in vanilla. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/perspective.rs | 11 ++ crates/horizon-client/src/mobs.rs | 33 ++++ crates/horizon-client/src/mobs/anim.rs | 152 ++++++++++++++++++ crates/horizon-client/src/mobs/render.rs | 36 +++-- 4 files changed, 221 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index bb463547f..e6ccb574f 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -313,6 +313,15 @@ impl Game<'_> { .map_or(25, |s| Self::charge_ticks(s).max(1)) as i32; let attack = (self.swing.old_animation, self.swing.animation); let swinging = self.swing.swinging(); + // currentSwing.hand().asArm(mainArm). + let swing_right_arm = swinging.then(|| { + (self.swing.attack_hand() == horizon_client::first_person::Hand::Main) + != self.settings.main_hand_left + }); + // LivingEntity.isVisuallySwimming and Entity.isInWater. + let visually_swimming = + p.pose == Pose::Swimming || (!p.fall_flying && p.pose == Pose::FallFlying); + let in_water = p.fluids.was_touching_water; let (yaw, pitch) = (self.yaw, self.pitch); let main = self.inventory[self.selected] .as_ref() @@ -378,6 +387,8 @@ impl Game<'_> { m.extra.charged = charged; m.extra.ints[5] = charge_duration; m.extra.elytra.tick(fall_flying, crouching, velocity); + m.extra.swim.tick(visually_swimming, in_water); + m.extra.swing_right_arm = swing_right_arm; m.hurt_time = hurt; } /// Whether the player's own model shows in the world view. diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 8b51593bc..c894cf471 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -690,6 +690,10 @@ pub struct Extra { pub fall_fly_ticks: i32, pub main_hand_left: bool, pub elytra: ElytraAnimation, + pub swim: SwimAnimation, + /// The arm the current swing moves (`currentSwing.hand().asArm`): `Some(true)` + /// for the right arm. + pub swing_right_arm: Option, pub flag: bool, pub flag2: bool, /// Species scratch values (the wither's head targets and clocks). @@ -2068,6 +2072,35 @@ impl ElytraAnimation { } } +/// `LivingEntity.swimAmount` and the render state the swimming pose reads +/// (`isVisuallySwimming`, `isInWater`). +#[derive(Clone, Copy, Debug, Default)] +pub struct SwimAnimation { + pub old: f32, + pub amount: f32, + /// `isVisuallySwimming`: in the swimming pose (or still in the gliding + /// pose after a glide ended). + pub visually: bool, + pub in_water: bool, +} +impl SwimAnimation { + /// `LivingEntity.updateSwimAmount`. + pub fn tick(&mut self, visually: bool, in_water: bool) { + self.old = self.amount; + self.amount = if visually { + (self.amount + 0.09).min(1.0) + } else { + (self.amount - 0.09).max(0.0) + }; + self.visually = visually; + self.in_water = in_water; + } + /// `LivingEntity.getSwimAmount`. + pub fn amount(&self, partial: f32) -> f32 { + self.old + partial * (self.amount - self.old) + } +} + #[cfg(test)] mod elytra_tests { use super::*; diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 161db24f9..4f16dcffb 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -276,6 +276,12 @@ pub struct Hum { pub charge: (f32, f32), /// `PiglinModel.setupAttackAnimation`: swing a held weapon down. pub weapon_swing: bool, + /// `swimAmount` at this frame. + pub swim: f32, + /// `isUsingItem`: the swim stroke leaves the arms alone. + pub using_item: bool, + /// The arm the current swing moves (`Some(true)` for the right one). + pub swing_right_arm: Option, } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -290,6 +296,9 @@ impl Hum { holding: false, charge: (0.0, 0.0), weapon_swing: false, + swim: 0.0, + using_item: false, + swing_right_arm: None, } } } @@ -455,6 +464,86 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { } bob(p, "right_arm", s.age, 1.0); bob(p, "left_arm", s.age, -1.0); + if h.swim > 0.0 { + swim(p, s.pos, h); + } +} +/// `Mth.rotLerpRad`. +fn rot_lerp_rad(a: f32, from: f32, to: f32) -> f32 { + let mut diff = to - from; + while diff < -PI { + diff += PI * 2.0; + } + while diff >= PI { + diff -= PI * 2.0; + } + from + a * diff +} +/// `HumanoidModel.setupSwimAnimation`: the stroke of both arms over 26 +/// walk-animation units, the head down and a slow flutter kick. The left arm +/// eases the short way round, the right one linearly, as in vanilla. +fn swim(p: &mut Poses, pos: f32, h: &Hum) { + let amount = h.swim; + if !h.fall_flying { + let x = p.get("head")[3]; + p.xrot( + "head", + rot_lerp_rad(amount, x, -std::f32::consts::FRAC_PI_4), + ); + } + let swim_pos = pos % 26.0; + let right_amount = if h.swing_right_arm == Some(true) { + 0.0 + } else { + amount + }; + let left_amount = if h.swing_right_arm == Some(false) { + 0.0 + } else { + amount + }; + let lerp = |a: f32, from: f32, to: f32| from + a * (to - from); + let quadratic = |x: f32| -65.0 * x + x * x; + if !h.using_item { + // Targets (x, y, z) for the left and right arm. + let targets = if swim_pos < 14.0 { + let stroke = 1.870_796_4 * quadratic(swim_pos) / quadratic(14.0); + Some(([0.0, PI, PI + stroke], [0.0, PI, PI - stroke])) + } else if swim_pos < 22.0 { + let t = (swim_pos - 14.0) / 8.0; + let x = PI / 2.0 * t; + Some(( + [x, PI, 5.012_389 - 1.870_796_4 * t], + [x, PI, 1.270_796_3 + 1.870_796_4 * t], + )) + } else if swim_pos < 26.0 { + let t = (swim_pos - 22.0) / 4.0; + let x = PI / 2.0 - PI / 2.0 * t; + Some(([x, PI, PI], [x, PI, PI])) + } else { + None + }; + if let Some((left, right)) = targets { + for (i, target) in left.into_iter().enumerate() { + let angle = &mut p.get("left_arm")[3 + i]; + *angle = rot_lerp_rad(left_amount, *angle, target); + } + for (i, target) in right.into_iter().enumerate() { + let angle = &mut p.get("right_arm")[3 + i]; + *angle = lerp(right_amount, *angle, target); + } + } + } + let x = p.get("left_leg")[3]; + p.xrot( + "left_leg", + lerp(amount, x, 0.3 * (pos * 0.333_333_34 + PI).mcos()), + ); + let x = p.get("right_leg")[3]; + p.xrot( + "right_leg", + lerp(amount, x, 0.3 * (pos * 0.333_333_34).mcos()), + ); } /// Apply the mob's model animation to `p`. pub fn setup( @@ -580,6 +669,9 @@ pub fn setup( } h.crouching = m.extra.crouching; h.passenger = m.extra.passenger; + h.swim = m.extra.swim.amount(s.partial); + h.using_item = m.extra.using_item > 0; + h.swing_right_arm = m.extra.swing_right_arm; humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. @@ -710,4 +802,64 @@ mod flight_pose_tests { assert_eq!(flight.get("head")[3], -std::f32::consts::FRAC_PI_4); assert_eq!(flight.get("right_leg")[3], ground.get("right_leg")[3] / 8.0); } + + #[test] + fn swimming_strokes_the_arms_and_kicks() { + let state = State { + pos: 7.0, + speed: 1.0, + age: 0.0, + y_rot: 0.0, + x_rot: 30.0, + swing: 0.0, + baby: false, + partial: 0.0, + }; + let make = || Poses { + map: ["head", "right_arm", "left_arm", "right_leg", "left_leg"] + .into_iter() + .map(|n| (n.to_string(), [0.0; 9])) + .collect(), + dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), + }; + let same_angle = |a: f32, b: f32| ((a - b + PI).rem_euclid(PI * 2.0) - PI).abs() < 1e-5; + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + h.swim = 1.0; + let mut p = make(); + humanoid(&mut p, &state, &h); + // Mid-stroke: both arms sweep out from overhead by the quadratic. + let stroke = 1.870_796_4 * (-65.0 * 7.0 + 49.0) / (-65.0 * 14.0 + 196.0); + assert_eq!(p.get("right_arm")[5], PI - stroke); + assert!(same_angle(p.get("left_arm")[5], PI + stroke)); + assert_eq!(p.get("right_arm")[4], PI); + assert!(same_angle(p.get("head")[3], -std::f32::consts::FRAC_PI_4)); + assert!(same_angle( + p.get("right_leg")[3], + 0.3 * (7.0f32 * 0.333_333_34).mcos() + )); + // Using an item keeps the arms; a swing frees its own arm only. + let mut using = make(); + h.using_item = true; + humanoid(&mut using, &state, &h); + assert_eq!(using.get("right_arm")[4], 0.0); + h.using_item = false; + h.swing_right_arm = Some(true); + let mut swinging = make(); + humanoid( + &mut swinging, + &State { + swing: 0.5, + ..state + }, + &h, + ); + assert!(swinging.get("right_arm")[4] < 1.0); + assert!(same_angle(swinging.get("left_arm")[4], PI)); + // Out of the pose nothing changes. + let mut dry = make(); + humanoid(&mut dry, &state, &Hum::new(ArmPose::Empty, ArmPose::Empty)); + assert_eq!(dry.get("head")[3], 30.0f32.to_radians()); + } } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index e8120e92e..21ab88aa3 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -765,6 +765,17 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())), }; let mut base = origin * rotation; + if m.death_time > 0 && !super::creaking::tearing_down(m) { + let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) + .sqrt() + .min(1.0); + base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { + // isEntityUpsideDown + base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) + * glam::Mat4::from_rotation_z(PI); + } + // AvatarRenderer.setupRotations, after LivingEntityRenderer's. if m.extra.fall_flying { let ticks = m.extra.fall_fly_ticks as f32 + alpha; let scale = (ticks * ticks / 100.0).min(1.0); @@ -785,17 +796,20 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 (sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32, ); } - } - - if m.death_time > 0 && !super::creaking::tearing_down(m) { - let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) - .sqrt() - .min(1.0); - base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); - } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { - // isEntityUpsideDown - base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) - * glam::Mat4::from_rotation_z(PI); + } else if m.extra.swim.amount(alpha) > 0.0 { + // AvatarRenderer.setupRotations: tip forward with the swim amount, + // following the pitch in water, then lie along the swimming box. + let amount = m.extra.swim.amount(alpha); + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + let target = if m.extra.swim.in_water { + -90.0 - pitch + } else { + -90.0 + }; + base *= glam::Mat4::from_rotation_x((amount * target).to_radians()); + if m.extra.swim.visually { + base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.0, 0.3)); + } } base *= species_rotations(m, alpha); base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); From 57ee531c639e1e899d63a786fd878ad9cb1c76e4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 08:45:48 +0200 Subject: [PATCH 030/327] Host a server: a guide in docs/hosting.md, and the site's /server page built from it What works on main today (install, game files, first run, server.toml, the commands, the web panel, backups, services, Docker built by hand) and, plainly, what doesn't yet: offline mode only, no published image, no secure chat or locator bar, the open PRs that are coming. The site renders the guide into /server at build time, so it has one source. The CSP hashes now cover every page's inline script, so the privacy page's theme script is allowed too. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 3 +- docs/hosting.md | 306 +++++++++++++++++++++++++++++++++++++ website/Caddyfile | 3 +- website/README.md | 3 +- website/build.mjs | 16 +- website/public/sitemap.xml | 1 + website/src/index.html | 2 +- website/src/server.html | 31 ++++ 8 files changed, 356 insertions(+), 9 deletions(-) create mode 100644 docs/hosting.md create mode 100644 website/src/server.html diff --git a/docs/README.md b/docs/README.md index 7cf322042..9a5ea0483 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,7 +6,8 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. -- [Hosting a server](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. +- [Host a server](hosting.md): install `horizon-server`, prepare the game files, first run, `server.toml`, the commands, the web panel, backups, services and Docker; what works today and what doesn't yet. +- [Hosting a server: design](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. - [Agent control](agent-control.md): what AI agents can drive in the launcher and the game, and the design of the control socket, `horizon-ctl` and MCP. - [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. - [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it. diff --git a/docs/hosting.md b/docs/hosting.md new file mode 100644 index 000000000..483d1cfcb --- /dev/null +++ b/docs/hosting.md @@ -0,0 +1,306 @@ +# Host a server + +`horizon-server` hosts a Minecraft Java Edition 26.3 server with Horizon's own game as the engine: one native +program, no Java, one settings file, a command line, and a web panel. Vanilla 26.3 clients and Horizon clients +can join it. This page covers what works on `main` today and says plainly what doesn't yet. The design and the +plan are in [docs/server.md](docs/server.md). + +## Before you start + +- **It runs in offline mode only.** Today the server never checks Minecraft accounts: even with + `online_mode = true` it runs offline and says so when it starts. Anyone who can reach it can join under any + name, including a name on your whitelist. Run it on your LAN, on a tailnet (Tailscale, ZeroTier), or for + friends you trust. Don't open it to the internet. +- **Online mode is coming in two parts.** Checking accounts with Mojang's session servers is in review ([#587](https://github.com/ludovic111/horizon/pull/587), + and [#589](https://github.com/ludovic111/horizon/pull/589) for adding players to the whitelist and ops by account). With it, players who sign in with the + official Minecraft launcher can join with their own accounts. Horizon's own client can't sign in to a + Microsoft account yet: that needs an Azure app registration and Mojang's approval, which the project doesn't + have yet ([docs/microsoft-account.md](docs/microsoft-account.md)). Until then Horizon players can join + offline servers only. +- **No secure chat.** Chat isn't signed. Vanilla clients show chat from the server as not secure. +- **No locator bar** for vanilla clients yet (coming). +- **Remote players stay in the Overworld.** Nether and End portals don't move remote players yet (in review: + [#668](https://github.com/ludovic111/horizon/pull/668), for a server with one player). +- **Vanilla's movement checks and chunk pacing** ("moved too quickly", sending chunks as fast as a client + acknowledges them) are in review ([#586](https://github.com/ludovic111/horizon/pull/586)). +- **No Docker image is published.** You build it yourself from the repository (below). Publishing an image + needs the project owner. +- Nothing of Mojang's is downloaded or shipped. The server reads the game files you prepare from your own copy + of Minecraft 26.3. + +## 1. Install + +Linux (x86-64) and macOS (Apple Silicon): + +```sh +curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh +``` + +Windows (x64), in PowerShell: + +```powershell +irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex +``` + +The script downloads the latest Horizon release for your computer from GitHub, checks it against the SHA-256 +GitHub publishes, and never asks for sudo or administrator rights. It installs: + +- the release in `~/.local/share/horizon/releases/` (Windows: `%LOCALAPPDATA%\Horizon`), with + `current` pointing at the one in use; +- `horizon-server` and `horizon-prepare` in `~/.local/bin` (Windows: added to your PATH); +- a `game-files` folder for the files you prepare, kept across updates. + +Options: `--version vX.Y.Z`, `--dir FOLDER`, `--bin FOLDER` (Windows: `-Version`, `-Dir`). Other systems, +such as Linux on ARM, build from source: `cargo build --release -p horizon-client --bin horizon-client -p +horizon-server` and keep both programs in one folder. + +The Horizon launcher also installs releases. Every release folder holds `horizon-server`, so you can run it +from there too. + +## 2. Prepare the game files + +Horizon reads Minecraft's data from your own copy of the game. You need Minecraft Java Edition 26.3, played +once from the official launcher on this computer, Java 25 (a JDK), and the 26.3 `server.jar`: it's the +`downloads.server.url` in your launcher's `versions/26.3/26.3.json`. Then: + +```sh +horizon-prepare --prepare --server-jar /path/to/server.jar +``` + +Add `--minecraft-dir PATH` if your launcher keeps the game elsewhere. The prepared files go to +`game-files`, which updates keep. + +**On a headless machine** (a VPS, a home server), prepare on your own computer instead, with the launcher or +`horizon-prepare`, and copy the prepared `26.3` folder to the server: into +`~/.local/share/horizon/game-files/horizon-client/26.3`, or into `resources/` in the server folder, or anywhere +`[engine] resources` in `server.toml` names. A folder copied this way needs a release newer than +v2026.10.17.05: older ones don't keep `registries.json` and `commands.json` with the prepared files, and the +server then stops with "registries.json not found next to the resources". Prepare again with a newer release. + +## 3. First run + +```sh +mkdir my-server && cd my-server +horizon-server init +``` + +`init` asks five things and writes `server.toml`: + +1. whether you agree to the [Minecraft EULA](https://aka.ms/MinecraftEULA): only a yes writes `eula=true`; +2. the world's name and an optional seed (an existing world or vanilla server folder is kept and its + `server.properties` imported); +3. the port, 25565 by default; +4. whether to use a whitelist (yes by default, as in vanilla) and who to add; +5. whether to make the first player an operator. + +It then tells you where it found the game and its files. Every question has a flag, so it also runs from a +script: + +```sh +horizon-server init --eula --world survival --seed 12345 --port 25565 --whitelist --player Alex --op Alex --yes +``` + +`--no-whitelist` turns the whitelist off. Since the server runs offline, the players you add get offline UUIDs, +as a vanilla server in offline mode gives them. + +Start the server in the foreground, with the console on your terminal (Ctrl-C stops it cleanly): + +```sh +horizon-server run +``` + +or in the background: + +```sh +horizon-server start +horizon-server status +``` + +```text +Running, up 29 s +TPS 20.0, MSPT 1.0 ms average, 3.1 ms P95 +0 of 20 players, 377 chunks loaded +RAM 1.42 GB, CPU 2 % of a core +``` + +Players join at your computer's address and the port (`192.168.1.20:25565`, or a tailnet name). Every +command takes `--dir FOLDER` to work on a server folder from elsewhere. + +## 4. Settings: `server.toml` + +You edit one file. The server writes vanilla's `server.properties` from it before every start, so the game +reads exactly what a vanilla server reads, and a vanilla server folder works as it is. + +```toml +[server] +motd = "A Minecraft Server" +port = 25565 +bind = "" # listen on every address, or only on this one (server-ip) +max_players = 20 +online_mode = true # not supported yet: the server runs offline and says so +whitelist = true +enforce_whitelist = false +view_distance = 10 +simulation_distance = 10 + +[world] +name = "world" +seed = "" # empty: a random seed on the first start +game_mode = "survival" +difficulty = "easy" +hardcore = false + +# Any other server.properties key, spelled as vanilla spells it: +[properties] +# spawn-protection = 16 + +[engine] +path = "" # the game program; empty: the one beside horizon-server +resources = "" # the prepared game files; empty: resources/ here, else the usual places +restart_on_crash = true + +[backups] +every = "6h" # 30m, 6h, 1d...; "0" turns automatic backups off +keep = 12 # automatic backups kept; backups made by hand are never deleted + +[panel] +bind = "127.0.0.1:8130" # this computer only, or a tailnet address (100.x); "" turns it off +allow_public = false +``` + +The defaults are vanilla 26.3's. Unknown keys and values vanilla would refuse are errors, so a typo stops the +start instead of being ignored. When the game changes a setting itself (`/whitelist on`), the change is copied +back into `server.toml` when it stops, and your comments are kept. Changes to the file apply at the next +restart: there is no live reload yet. + +Already have a vanilla server? Run `horizon-server init` in its folder, or `horizon-server import +server.properties` to write `server.toml` from it. The world, `ops.json`, `whitelist.json` and the ban lists +keep vanilla's names and formats, so going back to vanilla works too. + +## 5. Commands + +```text +horizon-server init first run +horizon-server run in the foreground, with the console; Ctrl-C stops it +horizon-server start | stop | restart in the background (its output goes to logs/supervisor.log) +horizon-server status [--json] up or not, TPS, MSPT, players, chunks, RAM, CPU +horizon-server cmd COMMAND... one console command, and what it answers +horizon-server logs [-f] [-n N] the log; -f follows it +horizon-server op|deop NAME +horizon-server whitelist on|off|list +horizon-server whitelist add|remove NAME +horizon-server backup [NAME] back up now +horizon-server backups list the backups +horizon-server restore BACKUP [--yes] +horizon-server service install|uninstall|print [--system] +horizon-server panel a one-time login link for the web panel +horizon-server import FILE server.toml from a vanilla server.properties +``` + +While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so they act exactly as vanilla's +console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through +`cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`. + +The server restarts the game by itself if it crashes: after 5 s, then waiting longer each time, up to 5 +minutes. It keeps the crash report and gives up after 5 crashes in 10 minutes, and `status` says why. + +Coming: `update` and `rollback`, `console` (attach to a server running in the background), `ban` and +`pardon` as their own commands, and `mcp` (an MCP server so an AI assistant can run the server). + +## 6. Web panel + +The panel runs inside `horizon-server` while the server runs. It shows live TPS, MSPT, RAM and CPU graphs for +the last 10 minutes, the players with their ping (and a kick button), the console with a command line, and the +backups (back up now, restore with a confirmation), with Restart and Stop. + +```sh +horizon-server panel +``` + +prints a login link that works once, for 10 minutes. The panel listens on `127.0.0.1:8130`, this computer +only. To reach it from your other devices: + +- put your tailnet address in `[panel] bind` (for example `bind = "100.101.102.103:8130"`), or +- forward the port over SSH: `ssh -L 8130:127.0.0.1:8130 your-server`, then open the link on your computer. + +Any other address, such as `0.0.0.0` or a public IP, is refused unless you set `allow_public = true`, and +even then the panel warns at every start. It has no passwords to leak: whoever can read the server folder can +make a login link, and no one else can. Never put it on the open internet. + +## 7. Backups + +```sh +horizon-server backup before-the-update +horizon-server backups +horizon-server restore before-the-update +``` + +A backup zips the world, vanilla's files and `server.toml` into `backups/`. A running server saves first and +stays up: players don't notice. Automatic backups run on the `[backups] every` schedule while the server runs, +and the oldest automatic ones beyond `keep` are deleted. Backups you make by hand are never deleted. + +`restore` takes a backup's file name, a unique start of it, or the name you gave it. It moves the current +world aside to `backups/replaced-