From 606efe5af0a642b4ec08b6d64078da12366ab336 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 13:16:54 +0600 Subject: [PATCH 01/31] Animate remote squid bodies and tentacles from server velocity Run the client branch of Squid.aiStep, preserve authoritative movement and synchronize tentacle-cycle resets with entity event 19. Co-Authored-By: OpenAI GPT-6.1 Sol --- crates/horizon-client/examples/probe/main.rs | 2 + .../examples/probe/squid_client_probe.rs | 51 +++++++++++++ crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/remote.rs | 7 ++ crates/horizon-client/src/mobs.rs | 5 ++ crates/horizon-client/src/mobs/aquatic.rs | 61 +++++++++++++--- .../parity/VanillaSquidClientOracle.java | 73 +++++++++++++++++++ tools/test_squid_client_parity.py | 47 ++++++++++++ 8 files changed, 236 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-client/examples/probe/squid_client_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java create mode 100644 tools/test_squid_client_parity.py diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs index e80088fd0..e4cc68b9a 100644 --- a/crates/horizon-client/examples/probe/main.rs +++ b/crates/horizon-client/examples/probe/main.rs @@ -83,6 +83,7 @@ mod sound_engine_fixture; mod sound_event_fixture; mod spawn_rules_fixture; mod sprint_probe; +mod squid_client_probe; mod subtitle_fixture; mod tab_list_fixture; mod team_rules_fixture; @@ -107,6 +108,7 @@ probes! { block_transform_fixture, breaking_fixture, camera_probe, + squid_client_probe, cauldron_fixture, chat_screen_fixture, cloud_fixture, diff --git a/crates/horizon-client/examples/probe/squid_client_probe.rs b/crates/horizon-client/examples/probe/squid_client_probe.rs new file mode 100644 index 000000000..f9f9c9b2c --- /dev/null +++ b/crates/horizon-client/examples/probe/squid_client_probe.rs @@ -0,0 +1,51 @@ +use horizon_client::{ + Result, + mobs::{Mob, MobTypes, aquatic}, +}; +use horizon_core::geometry::Vec3; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, + sync::Arc, +}; + +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let types = MobTypes::load(&root)?; + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let kind = Arc::new( + types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(), + ); + let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0); + mob.fluids.in_water = row["water"].as_bool().unwrap(); + mob.velocity = Vec3::new( + row["x"].as_f64().unwrap(), + row["y"].as_f64().unwrap(), + row["z"].as_f64().unwrap(), + ); + mob.body_yaw = row["body"].as_f64().unwrap() as f32; + for (i, value) in row["v"].as_array().unwrap().iter().enumerate() { + mob.anim.v[i] = value.as_f64().unwrap() as f32; + } + if row["reset"].as_bool().unwrap() { + aquatic::squid_cycle_event(&mut mob); + } + let velocity = mob.velocity; + aquatic::squid_client_step(&mut mob); + assert_eq!( + velocity, mob.velocity, + "a remote animation must preserve packet velocity" + ); + write!(out, "{:08x}", mob.body_yaw.to_bits())?; + for value in &mob.anim.v[..6] { + write!(out, " {:08x}", value.to_bits())?; + } + writeln!(out)?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index be7923037..cc45faf78 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -810,6 +810,7 @@ impl Game<'_> { pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { + MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at), MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3a2dd1d69..547099cfe 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2174,6 +2174,11 @@ impl Game<'_> { { horizon_client::mobs::rabbit::hop_event(m); } + if p.event == 19 + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + horizon_client::mobs::aquatic::squid_cycle_event(m); + } // EntityEvent.DEATH: start the death animation. if p.event == 3 && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) @@ -3581,6 +3586,8 @@ impl Game<'_> { } else if m.alive() { m.body_rotation_tick(); } + // Squid.aiStep follows LivingEntity's interpolation and head turn. + horizon_client::mobs::aquatic::squid_client_step(m); // WalkAnimationState.update from the horizontal distance moved. let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..393ced4d1 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -868,6 +868,11 @@ pub struct Mob { /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] pub enum MobEvent { + /// Squid.handleEntityEvent(19), resetting the remote tentacle cycle. + SquidCycle { + mob: u32, + at: [f64; 3], + }, /// Rabbit entity event 1, sent only when a ground jump actually happens. RabbitHop { mob: u32, diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index dc80c6ea4..3f86d8edc 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -234,12 +234,40 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// Squid.aiStep: tentacle cycle, propulsion and body rotation. fn squid_ai_step(m: &mut Mob) { + squid_step(m, false); +} + +/// Squid.aiStep also runs on remote entities: animate from packet velocity, +/// without running goals or replacing that velocity with the server's movement vector. +pub fn squid_client_step(m: &mut Mob) { + if matches!(m.species(), Species::Squid | Species::GlowSquid) { + m.anim.vo = m.anim.v; + squid_step(m, true); + } +} + +/// Squid.handleEntityEvent(19): begin the next server-synchronised tentacle cycle. +pub fn squid_cycle_event(m: &mut Mob) { + if matches!(m.species(), Species::Squid | Species::GlowSquid) { + m.anim.v[TENTACLE_MOVEMENT] = 0.0; + } +} + +fn squid_step(m: &mut Mob, client: bool) { let v = &mut m.anim.v; v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED]; - if v[TENTACLE_MOVEMENT] > PI * 2.0 { - v[TENTACLE_MOVEMENT] -= PI * 2.0; - if m.random.next_int_bound(10).unwrap_or(1) == 0 { - m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + if f64::from(v[TENTACLE_MOVEMENT]) > std::f64::consts::TAU { + if client { + v[TENTACLE_MOVEMENT] = PI * 2.0; + } else { + v[TENTACLE_MOVEMENT] -= PI * 2.0; + if m.random.next_int_bound(10).unwrap_or(1) == 0 { + m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + } + m.outbox.push(MobEvent::SquidCycle { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + }); } } let v = &mut m.anim.v; @@ -248,28 +276,39 @@ fn squid_ai_step(m: &mut Mob) { let scale = v[TENTACLE_MOVEMENT] / PI; v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25; if scale > 0.75 { - let mv = m.extra.vector; - m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + if !client { + let mv = m.extra.vector; + m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + } m.anim.v[ROTATE_SPEED] = 1.0; } else { m.anim.v[ROTATE_SPEED] *= 0.8; } } else { v[TENTACLE_ANGLE] = 0.0; - m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + if !client { + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + } m.anim.v[ROTATE_SPEED] *= 0.99; } let mv = m.velocity; let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt(); - m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1; + m.body_yaw += (-(horizon_core::geometry::trig::atan2(mv.x, mv.z) as f32) * 57.295776 + - m.body_yaw) + * 0.1; m.yaw = m.body_yaw; let v = &mut m.anim.v; v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5; - v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1; + v[X_BODY_ROT] += (-(horizon_core::geometry::trig::atan2(horizontal, mv.y) as f32) + * 57.295776 + - v[X_BODY_ROT]) + * 0.1; } else { v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25; - let yd = m.velocity.y - m.kind.gravity; - m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + if !client { + let yd = m.velocity.y - m.kind.gravity; + m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + } let v = &mut m.anim.v; v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java new file mode 100644 index 000000000..66b833c54 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java @@ -0,0 +1,73 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonParser; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.Holder; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.animal.squid.Squid; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +/** Runs the real Squid.aiStep, with unrelated movement/world services controlled. */ +public final class VanillaSquidClientOracle { + static Field field(Class owner, String name) throws Exception { + var f = owner.getDeclaredField(name); f.setAccessible(true); return f; + } + static final class Shell extends Squid { + Level world; boolean water; + Shell() { super(EntityTypes.SQUID, null); } + @Override public Level level() { return world; } + @Override public boolean isAgeLocked() { return true; } + @Override public boolean isInWater() { return water; } + @Override protected boolean isImmobile() { return true; } + @Override protected void applyInput() {} + @Override public boolean isEffectiveAi() { return false; } + @Override public boolean isFallFlying() { return false; } + @Override public boolean hasEffect(Holder effect) { return false; } + @Override public LivingEntity getControllingPassenger() { return null; } + @Override public void calculateEntityAnimation(boolean flying) {} + @Override protected void pushEntities() {} + } + static String bits(float value) { return String.format("%08x", Float.floatToIntBits(value)); } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + var uf = field(u, "theUnsafe"); var unsafe = uf.get(null); + var allocate = u.getMethod("allocateInstance", Class.class); + var world = (ClientLevel) allocate.invoke(unsafe, ClientLevel.class); + field(Level.class, "isClientSide").setBoolean(world, true); + String[] names = {"tentacleMovement", "tentacleAngle", "xBodyRot", "zBodyRot", "tentacleSpeed", "rotateSpeed"}; + Field[] values = new Field[names.length]; + for (int i = 0; i < names.length; i++) values[i] = field(Squid.class, names[i]); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + for (var line : (Iterable) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var m = (Shell) allocate.invoke(unsafe, Shell.class); + m.world = world; field(Entity.class, "level").set(m, world); m.water = row.get("water").getAsBoolean(); + field(Entity.class, "type").set(m, EntityTypes.SQUID); + field(LivingEntity.class, "equipment").set(m, new EntityEquipment()); + field(Entity.class, "interpolationHandler").set(m, Proxy.newProxyInstance( + InterpolationHandler.class.getClassLoader(), new Class[]{InterpolationHandler.class}, + (proxy, method, arguments) -> method.getName().equals("hasActiveInterpolation") ? true : null)); + m.setBoundingBox(new AABB(0, 0, 0, 1, 1, 1)); + m.setDeltaMovement(new Vec3(row.get("x").getAsDouble(), row.get("y").getAsDouble(), row.get("z").getAsDouble())); + m.yBodyRot = row.get("body").getAsFloat(); + for (int i = 0; i < names.length; i++) values[i].setFloat(m, row.getAsJsonArray("v").get(i).getAsFloat()); + if (row.get("reset").getAsBoolean()) m.handleEntityEvent((byte)19); + m.aiStep(); + out.print(bits(m.yBodyRot)); + for (var f : values) out.print(" " + bits(f.getFloat(m))); + out.println(); + } + } + } +} diff --git a/tools/test_squid_client_parity.py b/tools/test_squid_client_parity.py new file mode 100644 index 000000000..9ded209aa --- /dev/null +++ b/tools/test_squid_client_parity.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Compare the real Squid.aiStep client branch and cycle event with Rust.""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def make_input(build): + rng = random.Random(1684) + rows = [] + for species in ('squid', 'glow_squid'): + for water in (False, True): + for reset in (False, True): + for velocity in ((0, 0, 0), (.1, 0, 0), (0, .1, 0), + (0, -.1, 0), (0, 0, -.1), (.1, .2, -.3)): + for movement in (0, 1, 2.4, 3.14, 4, 6.2, 6.4): + rows.append(dict(species=species, water=water, reset=reset, + x=velocity[0], y=velocity[1], z=velocity[2], + body=rng.uniform(-180, 180), + v=[movement, .2, -45, 33, .15, .8])) + for _ in range(1000): + rows.append(dict(species=rng.choice(('squid', 'glow_squid')), water=True, + reset=False, x=rng.uniform(.01, .2), y=rng.uniform(.01, .2), + z=rng.uniform(.01, .2), body=rng.uniform(-180, 180), + v=[rng.uniform(0, 7), 0, rng.uniform(-90, 90), + rng.uniform(0, 180), rng.uniform(.1, .2), rng.random()])) + path = build / 'inputs.jsonl' + path.write_text(''.join(json.dumps(row) + '\n' for row in rows)) + return path, len(rows) + + +def main(): + harness.differential( + 'rust-squid-client-parity', 'VanillaSquidClientOracle', 'squid_client_probe', + make_input, + 'Actual Squid.aiStep on a client with controlled inherited movement/world services. ' + 'Checks water/air body rotation and tentacle state, cycle clamping and event 19. ' + 'Glow squid uses the same inherited method; packet dispatch and rendering are separate.', + sources=[lab.ROOT / 'crates/horizon-client/src/mobs/aquatic.rs']) + + +if __name__ == '__main__': + main() From 66f32a7a3aab0c00faec4c2c487c3047890c337b Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:45:35 +0000 Subject: [PATCH 02/31] Persist forced chunks across world restarts Co-Authored-By: Codex GPT-6.1 Sol --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/saving.rs | 1 + .../horizon-client/src/game/world_loading.rs | 1 + crates/horizon-client/src/save.rs | 105 ++++++++++++++++- tools/singleplayer_forced_chunks_audit.py | 110 ++++++++++++++++++ 5 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 tools/singleplayer_forced_chunks_audit.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8f9c1957d..977bcaeca 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7968,6 +7968,7 @@ impl Game<'_> { /// (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.save.save_forced_chunks(&self.streaming.forced)?; self.streaming.save(&mut self.world, true); let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); @@ -10082,6 +10083,7 @@ impl Game<'_> { } /// Save the level in place: its changed chunks, its entities and its raids. fn save_level(&mut self, wait: bool) -> Result<()> { + self.save.save_forced_chunks(&self.streaming.forced)?; self.streaming.save(&mut self.world, wait); let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); diff --git a/crates/horizon-client/src/game/saving.rs b/crates/horizon-client/src/game/saving.rs index 378ffe9ce..1c6632562 100644 --- a/crates/horizon-client/src/game/saving.rs +++ b/crates/horizon-client/src/game/saving.rs @@ -179,6 +179,7 @@ impl Game<'_> { if keys.is_empty() { self.prune_entity_memory(); self.save_raids(); + self.save.save_forced_chunks(&self.streaming.forced)?; self.save_game_metadata()?; save.stage = Stage::Writes; } diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 0cea31fd0..ef47cc9c0 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -261,6 +261,7 @@ pub(super) fn make_streaming( res.threads(), ) }; + streaming.forced = save.load_forced_chunks(); streaming.radius = settings.render_distance; streaming.biome_blend = settings.biome_blend; streaming.smooth_lighting = settings.smooth_lighting; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..e93d6019b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -36,7 +36,7 @@ use horizon_world::{ worldgen::terrain::TerrainBlockStates, }; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, HashMap, HashSet}, fs, path::{Path, PathBuf}, sync::{ @@ -1613,6 +1613,9 @@ pub struct SaveDir { /// False in dimensions without skylight (no SkyLight layers are written). pub sky_light: bool, } +fn is_forced_ticket(ticket: &Tag) -> bool { + matches!(ticket.get("type"), Some(Tag::String(t)) if *t == JavaString::from("minecraft:forced")) +} impl SaveDir { pub fn new(root: PathBuf) -> Self { let sky_light = !root.ends_with("the_nether") && !root.ends_with("DIM-1"); @@ -1628,6 +1631,50 @@ impl SaveDir { sky_light, } } + /// 26.3's TicketStorage: persistent tickets live in each dimension's + /// data/minecraft/chunk_tickets.dat, with ChunkPos.CODEC's [x, z] int array. + pub fn load_forced_chunks(&self) -> HashSet<(i32, i32)> { + let Some(data) = read_saved_data(&self.root, "chunk_tickets") else { + return HashSet::new(); + }; + let Some(Tag::List(tickets)) = data.get("tickets") else { + return HashSet::new(); + }; + tickets + .iter() + .filter(|t| is_forced_ticket(t)) + .filter_map(|t| match t.get("chunk_pos")? { + Tag::IntArray(pos) if pos.len() == 2 => Some((pos[0], pos[1])), + _ => None, + }) + .collect() + } + pub fn save_forced_chunks(&self, forced: &HashSet<(i32, i32)>) -> Result<()> { + if forced.is_empty() && !saved_data_path(&self.root, "chunk_tickets").exists() { + return Ok(()); + } + let mut data = compound_or_empty(read_saved_data(&self.root, "chunk_tickets")); + // Preserve persistent tickets Horizon does not simulate. + let mut tickets = match data.get("tickets") { + Some(Tag::List(tickets)) => tickets + .iter() + .filter(|t| !is_forced_ticket(t)) + .cloned() + .collect::>(), + _ => Vec::new(), + }; + let mut chunks: Vec<_> = forced.iter().copied().collect(); + chunks.sort_unstable(); + tickets.extend(chunks.into_iter().map(|(x, z)| { + Tag::compound([ + ("type", Tag::String("minecraft:forced".into())), + ("level", Tag::Int(31)), // ChunkMap.FORCED_TICKET_LEVEL: ENTITY_TICKING. + ("chunk_pos", Tag::IntArray(vec![x, z])), + ]) + })); + put(&mut data, "tickets", Tag::List(tickets)); + write_saved_data(&self.root, "chunk_tickets", data) + } fn region_path(&self, folder: &str, rx: i32, rz: i32) -> PathBuf { region_path(&self.root, folder, rx, rz) } @@ -3436,6 +3483,62 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn forced_chunks_survive_dimension_restarts_and_removals() { + let root = std::env::temp_dir().join(format!("horizon-forced-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let dimensions = [ + "minecraft:overworld", + "minecraft:the_nether", + "minecraft:the_end", + ]; + for (i, dim) in dimensions.iter().enumerate() { + let save = SaveDir::new(dimension_dir(&root, dim)); + assert!(save.load_forced_chunks().is_empty()); + let forced = HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]); + save.save_forced_chunks(&forced).unwrap(); + } + for (i, dim) in dimensions.iter().enumerate() { + let path = dimension_dir(&root, dim); + let save = SaveDir::new(path.clone()); + let mut forced = save.load_forced_chunks(); + assert_eq!( + forced, + HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]) + ); + let mut data = read_saved_data(&path, "chunk_tickets").unwrap(); + let other = Tag::compound([ + ("type", Tag::String("minecraft:portal".into())), + ("level", Tag::Int(30)), + ("chunk_pos", Tag::IntArray(vec![7, -8])), + ("ticks_left", Tag::Long(42)), + ]); + if let Some(Tag::List(tickets)) = data.get_mut("tickets") { + assert!( + tickets + .iter() + .all(|t| t.get("level") == Some(&Tag::Int(31))) + ); + tickets.push(other.clone()); + } + write_saved_data(&path, "chunk_tickets", data).unwrap(); + forced.remove(&(-1, -1)); + save.save_forced_chunks(&forced).unwrap(); + drop(save); + let reopened = SaveDir::new(path.clone()); + assert_eq!(reopened.load_forced_chunks(), forced); + reopened.save_forced_chunks(&HashSet::new()).unwrap(); + assert!(SaveDir::new(path.clone()).load_forced_chunks().is_empty()); + assert_eq!( + read_saved_data(&path, "chunk_tickets") + .unwrap() + .get("tickets"), + Some(&Tag::List(vec![other])) + ); + } + fs::remove_dir_all(root).unwrap(); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { diff --git a/tools/singleplayer_forced_chunks_audit.py b/tools/singleplayer_forced_chunks_audit.py new file mode 100644 index 000000000..89fdd572b --- /dev/null +++ b/tools/singleplayer_forced_chunks_audit.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Check #1527: per-dimension /forceload add/remove across normal restarts. + +Build horizon-client and horizon-ctl with the fast profile first, then run: + python3 tools/singleplayer_forced_chunks_audit.py --case force-save +Runs both default server-thread and in-frame singleplayer, using scratch homes. +""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import time + +from agent_control_e2e import Cli +import lab + + +DIMENSIONS = ('the_nether', 'the_end', 'overworld') + + +def query(cli, dimension, expected): + since = cli('events')['last'] + cli('command', command='forceload query') + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + reply = cli('events', since=since) + for event in reply['events']: + text = event.get('text', '') + if event.get('event') != 'chat' or f'minecraft:{dimension}' not in text: + continue + if expected: + if all(f'[{x}, {z}]' in text for x, z in expected): + return + elif 'No force loaded chunks' in text: + return + time.sleep(0.1) + raise AssertionError(f'{dimension}: expected {expected}, got {reply}') + + +def run(bin_dir, resources, in_frame): + with tempfile.TemporaryDirectory(prefix='hz-force-save-') as scratch: + work = Path(scratch) + previous = None + for stage in range(3): + # Every process gets fresh homes; copy only this fixture's saved world. + env = lab.game_env({k: v for k, v in os.environ.items() if k not in ( + 'HORIZON_HOME', 'HORIZON_LAUNCHER_HOME', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME')}) + home = Path(env['HORIZON_HOME']) + if previous is not None: + shutil.copytree(previous, home / 'saves') + socket = work / f'{stage}.sock' + cli = Cli(bin_dir / 'horizon-ctl', socket, home, env) + args = [str(bin_dir / 'horizon-client'), '--resources', str(resources), + '--world', 'forced', '--creative', '--seed', '4242', '--offscreen', + '--render-distance', '4', '--control', '--control-socket', str(socket)] + if in_frame: + args.append('--in-frame') + with (work / f'{stage}.log').open('w') as log: + process = subprocess.Popen(args, cwd=home, env=env, stdout=log, stderr=log) + try: + deadline = time.monotonic() + 120 + while not socket.exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError('game did not open its control socket') + time.sleep(0.1) + cli('wait_ready', seconds=240) + for i, dim in enumerate(DIMENSIONS): + cli('command', command=f'execute in minecraft:{dim} run tp @s 0 100 0') + for _ in range(30): + cli('wait', ticks=20) + if cli('state').get('dimension') == f'minecraft:{dim}': + break + else: + raise AssertionError(f'did not enter {dim}') + cli('wait_ready', seconds=240) + expected = [(i - 1, -1)] if stage == 1 else [] + query(cli, dim, expected) + if stage == 0: + cli('command', command=f'forceload add {(i - 1) * 16} -1') + query(cli, dim, [(i - 1, -1)]) + elif stage == 1: + cli('command', command=f'forceload remove {(i - 1) * 16} -1') + query(cli, dim, []) + cli('quit') + assert process.wait(timeout=120) == 0 + except Exception: + log.flush() + print((work / f'{stage}.log').read_text(errors='replace')[-6000:]) + raise + finally: + if process.poll() is None: + process.terminate() + process.wait(timeout=30) + previous = home / 'saves' + print(f'PASS force-save: {"in-frame" if in_frame else "server-thread"}, three dimensions, add/remove/restart') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--case', choices=['force-save'], default='force-save') + parser.add_argument('--bin-dir', type=Path, default=Path(__file__).resolve().parents[1] / 'target/fast') + args = parser.parse_args() + for in_frame in (False, True): + run(args.bin_dir.resolve(), lab.RESOURCES.resolve(), in_frame) + + +if __name__ == '__main__': + main() From fb9b26a06cf72d8d9f61fb260d9db76937623713 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 08:35:02 +0100 Subject: [PATCH 03/31] Work out the creative grid's stacks once per tab or search, not every frame With the creative inventory open, every frame cloned all the tabs with their stacks (twice), and items() cloned the selected tab's stacks again on each of its three or four calls a frame; on the search tab each call ran the whole search again, building every stack's localised name. That took the frame rate from about 1,900 to 980 with the inventory open and 340 while searching (#1953). Vanilla fills ItemPickerMenu.items when the tab or the search changes (selectTab, refreshSearchResults): the grid's stacks are now kept until the tab, the search text or the language changes, and the screen draws the tabs without copying their stacks. --- crates/horizon-client/src/creative.rs | 75 +++++++++++++++++++++++---- crates/horizon-client/src/game.rs | 5 +- 2 files changed, 68 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 249e40b11..95d32ac90 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -3,7 +3,12 @@ //! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab. use crate::{Result, items::ItemStack}; use serde_json::Value; -use std::{collections::HashMap, fs, path::Path}; +use std::{ + collections::HashMap, + fs, + path::Path, + sync::{Arc, Mutex}, +}; #[derive(Clone, Debug)] pub struct Tab { @@ -42,6 +47,17 @@ pub struct Creative { /// The search tab's stacks, in its display order. search_items: Vec, search_index: Vec, + /// ItemPickerMenu.items: what the grid shows, filled when the tab or the + /// search changes (selectTab, refreshSearchResults), not on every frame. + shown: Mutex>, +} +/// The grid's stacks for one tab, search text and language. +struct Shown { + tab: usize, + search: String, + /// A display name, so a language change refills the search results. + language: String, + items: Arc<[ItemStack]>, } /// Display names from the pinned en_us language file. #[derive(Default)] @@ -288,6 +304,7 @@ impl Creative { search_focused: std::time::Instant::now(), search_items, search_index, + shown: Mutex::new(None), } } /// Where a stack comes in the creative tabs (the search tab lists them @@ -300,6 +317,22 @@ impl Creative { .position(|s| s.same_item_same_components(stack)) .or_else(|| items.iter().position(|s| s.item == stack.item)) } + /// The tabs without their stacks: what the screen draws of them each frame. + pub fn tab_headers(&self) -> Vec { + self.tabs + .iter() + .map(|t| Tab { + id: t.id.clone(), + title: t.title.clone(), + icon: t.icon.clone(), + items: Vec::new(), + top: t.top, + column: t.column, + search: t.search, + inventory: t.inventory, + }) + .collect() + } pub fn tab(&self) -> &Tab { &self.tabs[self.selected.min(self.tabs.len() - 1)] } @@ -380,17 +413,39 @@ impl Creative { }) .collect() } - /// Items shown by the selected tab (the search tab filters by `search`). - pub fn items(&self, names: &Names) -> Vec { - let tab = self.tab(); - if tab.search { - return self - .search_results(&self.search, names) + /// Items shown by the selected tab (the search tab filters by `search`), + /// worked out again only when the tab, the search or the language changed. + pub fn items(&self, names: &Names) -> Arc<[ItemStack]> { + let tab = self.selected.min(self.tabs.len() - 1); + let search = if self.tab().search { + self.search.as_str() + } else { + "" + }; + let language = names.display_get("itemGroup.search").unwrap_or_default(); + let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shown.as_ref() + && s.tab == tab + && s.search == search + && s.language == language + { + return s.items.clone(); + } + let items: Arc<[ItemStack]> = if self.tab().search { + self.search_results(search, names) .into_iter() .map(|i| self.search_items[i].clone()) - .collect(); - } - tab.items.clone() + .collect() + } else { + self.tab().items.as_slice().into() + }; + *shown = Some(Shown { + tab, + search: search.to_owned(), + language, + items: items.clone(), + }); + items } pub fn rows(&self, names: &Names) -> usize { self.items(names).len().div_ceil(9) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8591c721f..4defa03ef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9721,8 +9721,9 @@ impl Game<'_> { fn draw_creative(&mut self, batch: &mut HudBatch) { let (ox, oy) = Self::creative_origin(batch); let selected = self.creative_screen.selected; - let tabs = self.creative_screen.tabs.clone(); - let tab = self.creative_screen.tab().clone(); + // Only what is drawn of the tabs: their stacks stay where they are. + let tabs = self.creative_screen.tab_headers(); + let tab = tabs[selected.min(tabs.len() - 1)].clone(); let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| { format!( "gui/sprites/container/creative_inventory/tab_{}_{}_{}", From 515c0bdb7d4361d702eb583b6c8f627991705834 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 09:36:10 +0100 Subject: [PATCH 04/31] Work out the level item models read once a frame draw_item_model built the client level state (dimension, game time, sun angle, moon phase, respawn) for every stack it drew, sampling the sky each time: about seventy times a frame with the creative inventory open, a fifth of the time spent on its items. Within a frame the level is the same for all of them, so it is kept for the frame (keyed by the frame, game time, day time and dimension). --- crates/horizon-client/src/game.rs | 8 ++++++++ crates/horizon-client/src/game/item_draw.rs | 20 +++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4defa03ef..c8de9e7e1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1266,6 +1266,13 @@ struct Game<'a> { /// Controllers (Horizon's own). pad: pad::Pads, frames: u64, + /// `item_level` for one frame, game time, day time and dimension. + item_level_cache: std::cell::RefCell< + Option<( + (u64, i64, i64, &'static str), + horizon_assets::item_model::LevelState, + )>, + >, /// Frames drawn with the player in the world, for `--world-frames`. world_frames: u64, fps: f32, @@ -12157,6 +12164,7 @@ impl<'a> Game<'a> { last_input: now, pad: Default::default(), frames: 0, + item_level_cache: Default::default(), world_frames: 0, fps: 0.0, fps_frames: 0, diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 1d79f077d..b6b7e2fb7 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -196,13 +196,31 @@ impl Game<'_> { skins: &self.skin_downloads, } } - /// The client level as item models read it. + /// The client level as item models read it: worked out once a frame (a + /// screen of items read the same level, its sky sampled once). pub(super) fn item_level(&self) -> LevelState { let dimension = match self.dim { Dim::Overworld => "minecraft:overworld", Dim::Nether => "minecraft:the_nether", Dim::End => "minecraft:the_end", }; + let key = ( + self.frames, + self.world.game_time, + self.world.day_time, + dimension, + ); + let mut cached = self.item_level_cache.borrow_mut(); + if let Some((at, level)) = cached.as_ref() + && *at == key + { + return level.clone(); + } + let level = self.level_state_now(dimension); + *cached = Some((key, level.clone())); + level + } + fn level_state_now(&self, dimension: &'static str) -> LevelState { let sky = self .dim_environment() .sample(self.world.day_time, None, None); From 0f6569070d13ba42d43db11711d62c572bf2b50d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 10:00:56 +0100 Subject: [PATCH 05/31] Draw a GUI item's vertices once while it stays in place Two costs a frame were repeated for every item a screen draws. ItemModels::components cloned the item's whole default component map (a JSON map of every default component) on every resolve, though most stacks carry no patch; it now borrows the defaults and copies only to apply a patch. And gui::draw submitted, culled, sorted and clipped every quad of a static item again each frame (hundreds of edge quads for a generated item, all facing sideways in the GUI), though the result for the same layers at the same position is the same; the HUD vertices of a static item are now kept per GUI position, keyed by its baked models, tints, transforms, the atlas and the exact position, and appended as they were. Items with a glint or a special model renderer are drawn as before. With the creative inventory open the HUD's share of a frame went from 0.66 ms to 0.23 ms. --- crates/horizon-assets/src/item_model.rs | 17 ++-- crates/horizon-client/src/item_render.rs | 4 + crates/horizon-client/src/item_render/gui.rs | 91 +++++++++++++++++++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs index 5999805eb..d567bc6ac 100644 --- a/crates/horizon-assets/src/item_model.rs +++ b/crates/horizon-assets/src/item_model.rs @@ -1031,19 +1031,22 @@ pub struct ItemModels { } impl ItemModels { - pub fn components(&self, stack: &StackView) -> Components { - let mut out = self - .prototypes - .get(&stack.item) - .cloned() - .unwrap_or_default(); + /// The stack's components: its item's defaults with the stack's patch on top. A stack + /// with no patch (most stacks a screen draws) borrows the defaults instead of copying them. + pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> { + static NONE: Components = BTreeMap::new(); + let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE); + if stack.patch.is_empty() { + return std::borrow::Cow::Borrowed(prototype); + } + let mut out = prototype.clone(); for (key, value) in &stack.patch { match value { Some(v) => out.insert(key.clone(), v.clone()), None => out.remove(key), }; } - out + std::borrow::Cow::Owned(out) } /// `ItemModelResolver.updateForTopItem`. pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem { diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index c2f5c8400..4f981b874 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -363,6 +363,9 @@ pub struct ItemRenderer { sprites: FileSprites, baked: Mutex>>, extents: Mutex>>>, + /// GUI items already drawn: the HUD vertices of a static item at a GUI position + /// (`gui::draw`), which are the same every frame it stays there. + pub(crate) gui_drawn: Mutex>>, /// Entity model layers of the special renderers. parts: HashMap, /// `colormap/grass.png` as ARGB. @@ -452,6 +455,7 @@ impl ItemRenderer { }, baked: Mutex::default(), extents: Mutex::default(), + gui_drawn: Mutex::default(), parts, grass, }) diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index e3d7cc876..ff25fff1d 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -8,7 +8,7 @@ use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost}; use crate::hud::{HudBatch, Rect}; use glam::{EulerRot, Mat4, Vec2, Vec3}; -use std::{collections::HashMap, f32::consts::PI}; +use std::{collections::HashMap, f32::consts::PI, sync::Arc}; mod depth; @@ -148,6 +148,95 @@ pub fn draw( if state.is_empty() { return; } + // A static item drawn where it was drawn before gives the same vertices: + // take them instead of submitting, sorting and clipping its quads again. + let key = DrawnKey::of(state, renderer, sprites, x, y); + if let Some(key) = &key + && let Some(drawn) = renderer + .gui_drawn + .lock() + .ok() + .and_then(|d| d.get(key).cloned()) + { + batch.vertices.extend_from_slice(&drawn); + return; + } + let start = batch.vertices.len(); + draw_now(state, renderer, sprites, host, batch, x, y, time); + if let Some(key) = key + && let Ok(mut drawn) = renderer.gui_drawn.lock() + { + // GUI positions and items are few; a long scroll through every tab stays bounded. + if drawn.len() >= DRAWN_LIMIT { + drawn.clear(); + } + drawn.insert(key, batch.vertices[start..].into()); + } +} + +/// Entries of `ItemRenderer::gui_drawn` before it starts over. +const DRAWN_LIMIT: usize = 8192; + +/// What a GUI item's vertices depend on: its layers' baked models (kept for the +/// renderer's life, so their addresses name them), tints and transforms, the +/// atlas, and the exact position. None for items whose drawing changes with time +/// or the host: a glint, or a special model renderer. +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct DrawnKey { + renderer: usize, + sprites: (usize, usize), + at: [u32; 2], + oversized: bool, + layers: Vec<(usize, Vec, [u32; 16], bool)>, +} +impl DrawnKey { + fn of( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + x: f32, + y: f32, + ) -> Option { + if state.animated { + return None; + } + let layers = state + .layers + .iter() + .map(|layer| match &layer.geometry { + super::LayerGeometry::Quads(baked) if layer.foil == super::FoilType::None => { + Some(( + Arc::as_ptr(baked) as usize, + layer.tints.clone(), + layer.matrix.to_cols_array().map(f32::to_bits), + layer.uses_block_light, + )) + } + _ => None, + }) + .collect::>>()?; + Some(Self { + renderer: std::ptr::from_ref(renderer) as usize, + sprites: (std::ptr::from_ref(sprites) as usize, sprites.len()), + at: [x.to_bits(), y.to_bits()], + oversized: state.oversized_in_gui, + layers, + }) + } +} + +/// [`draw`] without the cache. +#[allow(clippy::too_many_arguments)] +fn draw_now( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + host: &dyn SpecialHost, + batch: &mut HudBatch, + x: f32, + y: f32, + time: f32, +) { let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0)) * Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0)); let mut quads: Vec = Vec::new(); From 5389f72b9a7479d791f66977a25b6bfd1bc5d9cb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:24:41 +0100 Subject: [PATCH 06/31] Creative: work out the shown items again after a resource or language reload A resource pack can rename items without changing the Search label the cache was keyed on, so a search kept its old results until the query or tab changed. --- crates/horizon-client/src/creative.rs | 5 +++++ crates/horizon-client/src/game/options.rs | 1 + crates/horizon-client/src/game/packs.rs | 2 ++ 3 files changed, 8 insertions(+) diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 95d32ac90..bcc16a3dd 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -447,6 +447,11 @@ impl Creative { }); items } + /// Drop the shown items, so the next `items` works them out again: a + /// reload can rename items without changing the Search label. + pub fn forget_items(&self) { + *self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None; + } pub fn rows(&self, names: &Names) -> usize { self.items(names).len().div_ceil(9) } diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 243eced5c..81510004d 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -257,6 +257,7 @@ impl Game<'_> { lang::set(lang::Language::load(&[&root], code)); self.refresh_remote_language(); self.ui.chat.rescale(&self.gui.atlas); + self.creative_screen.forget_items(); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..0d9658e06 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -221,6 +221,8 @@ impl Game<'_> { self.apply_ui_settings(); } self.ui.chat.rescale(&self.gui.atlas); + // The creative screen survives the reload; item names may not. + self.creative_screen.forget_items(); Ok(()) } } From 858eeba1b850716e5779e1bea6c47d7908e713ad Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:59:33 +0100 Subject: [PATCH 07/31] Resource packs: hand the window surface to the reloaded renderer instead of creating a new one Applying packs dropped the window surface and created a new one for the renderer built on the same device. On Wayland with Mesa (RADV) the new surface came back lost (ERROR_SURFACE_LOST_KHR), the new renderer failed, and restoring the old one failed too, which crashed the game. --- crates/horizon-client/src/game/packs.rs | 2 +- crates/horizon-client/src/gfx.rs | 39 +++++++++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..50cd4dd5a 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -163,7 +163,7 @@ impl Game<'_> { self.pack.context.biomes.clone(), self.pack.context.light.clone(), )?; - // Keep the working GPU resources, but release its exclusive window surface. + // Keep the working GPU resources, and hand its window surface over. if let Some(renderer) = &mut self.renderer { renderer.release_surface(); } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 78f73bc8b..3e6428287 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -331,6 +331,10 @@ pub struct Renderer { adapter: wgpu::Adapter, /// The window's swapchain; `None` when rendering offscreen (`--offscreen`). surface: Option>, + /// The surface `release_surface` set aside for the renderer that replaces + /// this one on the same device: reused, not created again, as a new + /// surface for the window can come back lost (Wayland on Mesa). + spare_surface: std::sync::Mutex>>, /// The offscreen colour target, sized like `config`. offscreen: Option, /// Offscreen submissions still on the GPU: at most two frames run ahead. @@ -1026,7 +1030,15 @@ impl Renderer { surface: if offscreen { None } else { - Some(renderer.instance.create_surface(window.clone())?) + let spare = renderer + .spare_surface + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + Some(match spare { + Some(surface) => surface, + None => renderer.instance.create_surface(window.clone())?, + }) }, instance: renderer.instance.clone(), adapter: renderer.adapter.clone(), @@ -2296,6 +2308,7 @@ impl Renderer { instance, adapter, surface, + spare_surface: std::sync::Mutex::new(None), offscreen, in_flight: std::collections::VecDeque::new(), first_frame: if previous.is_none() { @@ -2472,18 +2485,32 @@ impl Renderer { view_formats: &config.view_formats, }) } - /// Release the window surface before another renderer uses the same window. + /// Hand the window surface over to the renderer that replaces this one on + /// the same device (it takes `spare_surface`). pub fn release_surface(&mut self) { - self.surface = None; + *self + .spare_surface + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) = self.surface.take(); } /// Reattach a window after surface loss or a failed renderer replacement. pub fn recreate_surface(&mut self) -> Result<()> { if self.offscreen.is_some() { return Ok(()); } - // Wayland allows only one tearing-control object per window surface. - self.release_surface(); - let surface = self.instance.create_surface(self.window.clone())?; + // The surface set aside for a replacement that failed, else a new one + // (Wayland allows only one tearing-control object per window surface, + // so the old one goes first). + let spare = self + .spare_surface + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + self.surface = None; + let surface = match spare { + Some(surface) => surface, + None => self.instance.create_surface(self.window.clone())?, + }; surface.configure(&self.device, &self.config); self.surface = Some(surface); Ok(()) From b0d378fe99acfdd2ac721976f93d82c7394a3288 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 17:16:07 +0600 Subject: [PATCH 08/31] Apply multiplayer motion packets to mobs for squid animation Co-Authored-By: Codex --- crates/horizon-client/src/game/remote.rs | 5 +- tests/test_remote_motion.py | 58 ++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/test_remote_motion.py diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 547099cfe..d245524a1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3050,7 +3050,10 @@ impl Game<'_> { /// blocks and primed TNT. fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) { let v = Vec3::new(velocity[0], velocity[1], velocity[2]); - if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + // Squid.aiStep derives its body pitch and roll from network motion. + m.velocity = v; + } else if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { d.velocity = v; } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) { f.velocity = v; diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py new file mode 100644 index 000000000..da059c60b --- /dev/null +++ b/tests/test_remote_motion.py @@ -0,0 +1,58 @@ +"""Exercise Entity motion delivery through the live multiplayer handler.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(shutil.which("rustc"), "requires Rust") +class RemoteMotionTests(unittest.TestCase): + def test_mob_velocity_reaches_squid_animation(self): + source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text() + start = source.index(" fn remote_motion(") + end = source.index(" fn apply_remote_health(", start) + fixture = r''' +#![allow(dead_code)] +use std::collections::HashMap; +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Vec3(f64, f64, f64); +impl Vec3 { fn new(x: f64, y: f64, z: f64) -> Self { Self(x,y,z) } } +#[derive(Default)] +struct Entity { id: u32, velocity: Vec3 } +#[derive(Default)] +struct Remote { pending_items: HashMap } +#[derive(Default)] +struct Creatures { projectiles: Vec } +#[derive(Default)] +struct Game { + mobs: Vec, dropped: Vec, falling: Vec, tnts: Vec, + creatures: Creatures, remote: Option, +} +impl Game { +METHOD +} +fn main() { + let mut game = Game::default(); + game.mobs.push(Entity { id: 42, ..Entity::default() }); + game.dropped.push(Entity { id: 43, ..Entity::default() }); + // AddEntity initial motion and subsequent SetEntityMotion share this handler. + for motion in [[0.12, -0.04, 0.08], [-0.05, 0.03, 0.2], [0.0; 3]] { + game.remote_motion(42, motion); + assert_eq!(game.mobs[0].velocity, Vec3::new(motion[0], motion[1], motion[2])); + assert_eq!(game.dropped[0].velocity, Vec3::default()); + } + game.remote_motion(43, [0.1, 0.2, 0.3]); + assert_eq!(game.dropped[0].velocity, Vec3::new(0.1, 0.2, 0.3)); + game.remote_motion(999, [1.0; 3]); // Untracked entity is harmless. +} +'''.replace("METHOD", source[start:end]) + with tempfile.TemporaryDirectory(prefix="remote-motion-") as directory: + path = Path(directory) + (path / "main.rs").write_text(fixture) + subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")], + check=True, capture_output=True, text=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) From 5b0ae25ff8ac27d0454ab59c3b80c0f42a08d33e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:49:39 +0100 Subject: [PATCH 09/31] Make thorns hurt the entity that hit the player Thorns picked the nearest living mob in the world. They now hurt the mob that caused the hit (or its projectile's owner), or the attacking player in a player-versus-player hit. --- crates/horizon-client/src/game/creatures.rs | 5 +- .../src/game/enchant_effects.rs | 48 +++++++++---------- crates/horizon-client/src/game/lan_pvp.rs | 28 ++++++++--- 3 files changed, 48 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..9a685066a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1536,7 +1536,10 @@ impl Game<'_> { } } self.hurt_armor(amount); - self.thorns(from); + // The thorns hurt the entity that caused the hit, if there is one. + if let Some(a) = attacker.or(owner) { + self.thorns(a); + } } if raised { self.after_block(outcome, amount, attacker, projectile); diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index aa9f75e06..7cdb3e526 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -255,23 +255,26 @@ impl Game<'_> { let _ = self.wind_burst(feet, radius, knockback, false, false); } } - /// Thorns on worn armor when a mob at `from` hits the player. - pub(super) fn thorns(&mut self, from: [f64; 3]) { - let attacker = self - .mobs - .iter() - .enumerate() - .filter(|(_, m)| m.alive()) - .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| { - (m.position.x - from[0]).powi(2) - + (m.position.y - from[1]).powi(2) - + (m.position.z - from[2]).powi(2) - }; - d(a.1).total_cmp(&d(b.1)) - }) - .map(|(i, _)| i); - let Some(attacker) = attacker else { return }; + /// Thorns on worn armor when the mob `attacker` hits the player: the + /// `affected: attacker` effect of `Enchantment.doPostAttack` hurts the + /// entity that caused the hit. + pub(super) fn thorns(&mut self, attacker: u32) { + let Some(index) = self.mobs.iter().position(|m| m.id == attacker && m.alive()) else { + return; + }; + for damage in self.thorns_damage() { + let m = &mut self.mobs[index]; + m.hurt(damage, None, &mut self.world.random); + let center = [m.position.x, m.position.y, m.position.z]; + self.audio + .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + } + } + /// The victim's side of thorns: for each worn piece whose chance comes up, + /// the damage to deal the attacker (`DamageEntity` min 1, max 5) and the + /// piece's wear (`ChangeItemDamage` 2). + pub(super) fn thorns_damage(&mut self) -> Vec { + let mut hits = Vec::new(); for slot in 0..4 { let Some(stack) = self.armor[slot].clone() else { continue; @@ -299,15 +302,7 @@ impl Game<'_> { if !ok { continue; } - // DamageEntity(min 1, max 5) and ChangeItemDamage(2). - let damage = 1.0 + self.world.random.next_float() * 4.0; - let center = { - let m = &mut self.mobs[attacker]; - m.hurt(damage, None, &mut self.world.random); - [m.position.x, m.position.y, m.position.z] - }; - self.audio - .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + hits.push(1.0 + self.world.random.next_float() * 4.0); if let Some(s) = self.armor[slot].as_mut() { s.damage += 2; if self @@ -320,6 +315,7 @@ impl Game<'_> { } } } + hits } /// `ExperienceOrb.repairPlayerItems`: returns the experience left over. pub(super) fn mending(&mut self, amount: u32) -> u32 { diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 467c4537c..518470dbb 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -37,6 +37,8 @@ pub(super) struct Strike { crit: bool, from: [f64; 3], sweep: Option<[f64; 3]>, + /// The attacking player: a guest's connection, or the host. + attacker: Option, /// `causeExtraKnockback`: its strength and direction (the attacker's /// yaw), and whether the hit is a sprinting knockback attack. knockback: (f32, f64, f64), @@ -124,6 +126,7 @@ impl Game<'_> { crit, from, sweep, + attacker: self.lan_acting, knockback: (strength, xd, zd), knockback_attack, team: self.player_team().cloned(), @@ -242,14 +245,27 @@ impl Game<'_> { if hurt && strength > 0.0 { g.knock_back_player(f64::from(strength), xd, zd); } - hurt + // The victim's thorns, dealt to the attacker below. + let thorns = if hurt { g.thorns_damage() } else { Vec::new() }; + (hurt, thorns) }; - let hurt = self.ui.rules.bool("pvp") - && harm - && match victim { + let (hurt, thorns) = if self.ui.rules.bool("pvp") && harm { + match victim { Victim::Host => land(self), - Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false), - }; + Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or_default(), + } + } else { + Default::default() + }; + // `Enchantment.doPostAttack`: thorns hurt the attacking player. + for damage in thorns { + match s.attacker { + None => self.hurt_player_by("minecraft:thorns", damage), + Some(conn) => { + self.guest_hit_by(host, conn, |g| g.hurt_player_by("minecraft:thorns", damage)); + } + } + } let sound = match (hurt, s.crit, s.scale > 0.9) { (false, ..) => "minecraft:entity.player.attack.nodamage", (true, true, _) => "minecraft:entity.player.attack.crit", From 7c16e83fdf200aa6eedb26e1dc6c0625712e7428 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:13:03 +0100 Subject: [PATCH 10/31] Key binds: a key bound to several mappings drives all of them --- crates/horizon-client/src/game.rs | 45 +++++++++-------- crates/horizon-client/src/keybinds.rs | 69 +++++++++++++++++++-------- 2 files changed, 76 insertions(+), 38 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..3d8392357 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11509,16 +11509,17 @@ impl ApplicationHandler for Game<'_> { } self.extras_mouse(button, pressed); self.mod_mouse_key(button, pressed); - match self.settings.keys.translate_mouse(button) { - Some(Err(b)) => self.play_mouse(b, pressed)?, - Some(Ok(k)) if pressed => { - self.keys.insert(k); - self.key_pressed(k)?; + for mapped in self.settings.keys.translate_mouse_all(button) { + match mapped { + Err(b) => self.play_mouse(b, pressed)?, + Ok(k) if pressed => { + self.keys.insert(k); + self.key_pressed(k)?; + } + Ok(k) => { + self.keys.remove(&k); + } } - Some(Ok(k)) => { - self.keys.remove(&k); - } - None => {} } } Screen::Inventory | Screen::Creative @@ -11754,18 +11755,24 @@ impl ApplicationHandler for Game<'_> { { self.smooth_camera = !self.smooth_camera; } - // Key binds: act as the default key of the bound mapping. - let key = match self.settings.keys.translate(key) { - Some(Ok(k)) => k, - Some(Err(button)) => { - if self.screen == Screen::Playing && !event.repeat { - self.play_mouse(button, event.state == ElementState::Pressed)?; + // Key binds: act as the default key of every mapping bound + // to it (KeyMapping.set drives them all). + for mapped in self.settings.keys.translate_all(key) { + match mapped { + Ok(k) => { + self.mapped_key( + k, + event.state == ElementState::Pressed, + event.repeat, + )?; + } + Err(button) => { + if self.screen == Screen::Playing && !event.repeat { + self.play_mouse(button, event.state == ElementState::Pressed)?; + } } - return Ok(()); } - None => return Ok(()), - }; - self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?; + } } WindowEvent::RedrawRequested => { self.observe_fullscreen(); diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index a59aa627c..99eb5a15a 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -320,49 +320,80 @@ impl KeyBinds { } /// The mapping a physical input triggers (first in list order). pub fn mapping_for(&self, key: &str) -> Option<&'static str> { - MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key) + self.mappings_for(key).next() + } + /// Every mapping a physical input triggers, in list order: like + /// `KeyMapping.set`/`click`, one key drives all the mappings bound to it. + pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { + MAPPINGS + .iter() + .map(|m| m.0) + .filter(move |n| self.get(n) == key) } /// Translate a physical key into the default key of the mapping it is /// bound to, so game code written against vanilla defaults follows the /// player's bindings. `None` means the key now does nothing; mouse - /// mappings bound to keys come back as `Err(button)`. + /// mappings bound to keys come back as `Err(button)`. The first of + /// [`KeyBinds::translate_all`]. pub fn translate(&self, key: KeyCode) -> Option> { + self.translate_all(key).into_iter().next() + } + /// The default keys of every mapping `key` is bound to (empty when it + /// now does nothing), so a key bound to two mappings (forward and + /// sprint) drives both, as `KeyMapping.set` does. + pub fn translate_all(&self, key: KeyCode) -> Vec> { let Some(name) = key_name(key) else { - return Some(Ok(key)); + return vec![Ok(key)]; }; - if let Some(mapping) = self.mapping_for(name) { - let default = Self::default_of(mapping); - if let Some(code) = key_code(default) { - return Some(Ok(code)); - } - return mouse_button(default).map(Err); + let bound: Vec<_> = self + .mappings_for(name) + .filter_map(|mapping| { + let default = Self::default_of(mapping); + match key_code(default) { + Some(code) => Some(Ok(code)), + None => mouse_button(default).map(Err), + } + }) + .collect(); + if !bound.is_empty() { + return bound; } // An unbound key whose default meaning was moved elsewhere is inert. if MAPPINGS .iter() .any(|(n, d, _)| *d == name && !self.is_default(n)) { - return None; + return Vec::new(); } - Some(Ok(key)) + vec![Ok(key)] } /// Translate a mouse button the same way (keys bound to mouse buttons). pub fn translate_mouse(&self, button: MouseButton) -> Option> { + self.translate_mouse_all(button).into_iter().next() + } + /// [`KeyBinds::translate_all`] for a mouse button. + pub fn translate_mouse_all(&self, button: MouseButton) -> Vec> { let name = mouse_name(button); - if let Some(mapping) = self.mapping_for(&name) { - let default = Self::default_of(mapping); - if let Some(b) = mouse_button(default) { - return Some(Err(b)); - } - return key_code(default).map(Ok); + let bound: Vec<_> = self + .mappings_for(&name) + .filter_map(|mapping| { + let default = Self::default_of(mapping); + match mouse_button(default) { + Some(b) => Some(Err(b)), + None => key_code(default).map(Ok), + } + }) + .collect(); + if !bound.is_empty() { + return bound; } if MAPPINGS .iter() .any(|(n, d, _)| *d == name && !self.is_default(n)) { - return None; + return Vec::new(); } - Some(Err(button)) + vec![Err(button)] } /// `AbstractContainerScreen.checkHotbarMouseClicked`: off hand, then hotbar. pub fn container_mouse_key(&self, button: MouseButton, creative: bool) -> Option { From 23d546c6d50051ce1ef6e0832cbb452ae9a60ad3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:24:20 +0100 Subject: [PATCH 11/31] Sleep: creative skips the monster check, bed reach and obstruction match vanilla, morning follows the time and weather rules --- crates/horizon-client/src/game.rs | 75 +++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..3e2c861d7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9594,8 +9594,9 @@ impl Game<'_> { rain.extend(snow_vertices); rain } - /// Player.startSleepInBed: night or thunder, no monsters within 8 blocks; - /// the bed becomes the respawn point either way. + /// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder, + /// and (outside creative) no monsters within 8 blocks; the bed becomes the + /// respawn point either way. fn try_sleep(&mut self, pos: [i32; 3]) { let Some(p) = self.player.as_ref() else { return; @@ -9610,22 +9611,40 @@ impl Game<'_> { .state(state) .map(|s| s.properties.clone()) .unwrap_or_default(); - let head = if props.get("part").map(String::as_str) == Some("foot") { - let d = facing_offset(props.get("facing").map_or("north", String::as_str)); - [pos[0] + d[0], pos[1], pos[2] + d[2]] + // The head and the foot: the block faces from the foot to the head. + let d = facing_offset(props.get("facing").map_or("north", String::as_str)); + let (head, foot) = if props.get("part").map(String::as_str) == Some("foot") { + ([pos[0] + d[0], pos[1], pos[2] + d[2]], pos) } else { - pos + (pos, [pos[0] - d[0], pos[1], pos[2] - d[2]]) }; - let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2) - + (p.position.z - f64::from(head[2]) - 0.5).powi(2)) - .sqrt(); - if dist > 3.0 { + // ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks + // sideways and 2 vertically of the head or the foot. + let reachable = |bed: [i32; 3]| { + (p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 + && (p.position.y - f64::from(bed[1])).abs() <= 2.0 + && (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 + }; + if !reachable(head) && !reachable(foot) { self.message = Some(( "You may not rest now; the bed is too far away".into(), Instant::now(), )); return; } + // ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the + // blocks above the head and the foot, as `in_wall` reads suffocating. + let blocked = [head, foot].iter().any(|bed| { + let f = self + .res + .facts() + .get(self.world.block(bed[0], bed[1] + 1, bed[2])); + f.full_collision && f.solid_render + }); + if blocked { + self.message = Some(("This bed is obstructed".into(), Instant::now())); + return; + } // In reach (bedInRange), day or night: setRespawnPosition( // RespawnConfig(the head, the player's yaw), not forced). It replaces // an anchor or a spawnpoint; respawning checks the bed is still there @@ -9655,13 +9674,15 @@ impl Game<'_> { )); return; } - let monsters = self.mobs.iter().any(|m| { - m.hostile() - && m.alive() - && (m.position.x - p.position.x).abs() < 8.0 - && (m.position.y - p.position.y).abs() < 5.0 - && (m.position.z - p.position.z).abs() < 8.0 - }); + // Creative players skip the monster check (`!this.isCreative()`). + let monsters = !self.creative + && self.mobs.iter().any(|m| { + m.hostile() + && m.alive() + && (m.position.x - p.position.x).abs() < 8.0 + && (m.position.y - p.position.y).abs() < 5.0 + && (m.position.z - p.position.z).abs() < 8.0 + }); if monsters { self.message = Some(( "You may not rest now; there are monsters nearby".into(), @@ -9711,14 +9732,20 @@ impl Game<'_> { } } // ServerLevel.tick: once enough of the players have slept 100 ticks, - // skip to morning, clear the weather and wake everyone. + // skip to morning if `advance_time` is on, wake everyone, and + // resetWeatherCycle if `advance_weather` is on and it is raining. if self.enough_slept() { - let t = self.world.day_time; - self.world.day_time = t + 24000 - t.rem_euclid(24000); - self.world.weather.raining = false; - self.world.weather.thundering = false; - self.world.weather.rain_time = 0; - self.world.weather.thunder_time = 0; + if self.ui.rules.bool("advance_time") { + let t = self.world.day_time; + self.world.day_time = t + 24000 - t.rem_euclid(24000); + } + // Level.isRaining: the rain level is above 0.2. + if self.ui.rules.bool("advance_weather") && self.world.weather.levels(1.0).0 > 0.2 { + self.world.weather.raining = false; + self.world.weather.thundering = false; + self.world.weather.rain_time = 0; + self.world.weather.thunder_time = 0; + } if self.sleeping.is_some() { self.wake_up(); } From 19c7a4a008e9d5bd01405adb9511b47a7fa9a51d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:25:37 +0100 Subject: [PATCH 12/31] Slime block slows a walking player (SlimeBlock.stepOn) While standing on slime with a vertical speed under 0.1 and not sneaking, the horizontal speed is scaled by 0.4 + |vertical speed| * 0.2 every tick. --- crates/horizon-client/src/motion.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..fcdd32cbd 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1083,7 +1083,7 @@ impl MotionWorld<'_, '_, '_> { /// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts /// to inside its movement path: powder snow (`PowderSnowBlock.entityInside` /// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes, - /// cactus and lit campfires, and the magma block it stands on + /// cactus and lit campfires, and the magma and slime blocks it stands on /// (`stepOn`). Pressure plates, tripwires and rails are the world tick's /// scan. pub fn apply_effects_from_blocks(&mut self) -> Result<()> { @@ -1141,14 +1141,22 @@ impl MotionWorld<'_, '_, '_> { // MagmaBlock's hot floor hurts unless it steps carefully (sneaks). if self.player.ground.on_ground { let on = self.legacy_on_position()?; - let magma = self - .assets - .registry - .state(self.block(on)) - .is_some_and(|s| s.name == "minecraft:magma_block"); + let under = self.assets.registry.state(self.block(on)); + let magma = under.is_some_and(|s| s.name == "minecraft:magma_block"); + let slime = under.is_some_and(|s| s.name == "minecraft:slime_block"); if magma && !self.player.shift_key_down { self.environment_hurt("minecraft:hot_floor", 1.0)?; } + // SlimeBlock.stepOn: a slow walk on slime drags the horizontal + // speed (the client moves its own player, so not the server's copy). + if slime && !damage_only && !self.player.shift_key_down { + let abs_delta_y = self.player.velocity.y.abs(); + if abs_delta_y < 0.1 { + let scale = 0.4 + abs_delta_y * 0.2; + self.player.velocity.x *= scale; + self.player.velocity.z *= scale; + } + } } let mut visited = std::collections::HashSet::new(); let mut entered = Vec::new(); From 71981a95a28738df145e1affadc60d069f906436 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:26:34 +0100 Subject: [PATCH 13/31] Weather: the rain and thunder fade runs even with the weather cycle off --- crates/horizon-client/src/game.rs | 3 ++- crates/horizon-client/src/world.rs | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..1e6bd7e4b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4227,8 +4227,9 @@ impl Game<'_> { if running { self.world.game_time += 1; if self.ui.rules.bool("advance_weather") { - self.world.weather.tick(&mut self.world.random); + self.world.weather.tick_timers(&mut self.world.random); } + self.world.weather.tick_levels(); self.tick_weather_effects(); } if self.ticks.is_multiple_of(6000) { diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index d73956d85..83083eba2 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -109,7 +109,9 @@ pub struct Weather { pub thunder_level: (f32, f32), } impl Weather { - pub fn tick(&mut self, random: &mut horizon_core::random::LegacyRandom) { + /// The timers of `advanceWeatherCycle`, which run only while + /// `advance_weather` is on. + pub fn tick_timers(&mut self, random: &mut horizon_core::random::LegacyRandom) { use horizon_core::random::RandomSource; let mut uniform = |min: i32, max: i32| min + random.next_int_bound(max - min + 1).unwrap_or(0); @@ -141,6 +143,10 @@ impl Weather { self.rain_time = uniform(12000, 180000); } } + } + /// The rain and thunder level fade at the end of `advanceWeatherCycle`, + /// which runs whatever `advance_weather` says, so `/weather` still shows. + pub fn tick_levels(&mut self) { self.thunder_level.0 = self.thunder_level.1; self.thunder_level.1 = (self.thunder_level.1 + if self.thundering { 0.01 } else { -0.01 }).clamp(0.0, 1.0); From d8fcebdf71076f0475ceb1ceb9349c652fa2ddcd Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:30:31 +0100 Subject: [PATCH 14/31] Match vanilla difficulty and survival rules for lightning fire --- crates/horizon-client/src/game/lightning.rs | 30 +++++++++------------ 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 916bd2a0a..297f372c5 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -162,11 +162,9 @@ impl Game<'_> { converted: Vec::new(), }); } - /// `spawnFire`: fire at the strike point and `extra` random neighbours. + /// `spawnFire`: fire at the strike point and `extra` random neighbours, + /// wherever `BaseFireBlock.getState` fire can survive. fn bolt_fire(&mut self, at: [f64; 3], extra: i32) { - if self.ui.difficulty < 2 { - return; - } let base = [ at[0].floor() as i32, at[1].floor() as i32, @@ -183,18 +181,13 @@ impl Game<'_> { if !self.res.facts().is_air(state) { continue; } - // BaseFireBlock.getState: soul fire on soul soil and sand. - let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2])); - let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") { - "minecraft:soul_fire" - } else { - "minecraft:fire" - }; - // FireBlock.canSurvive: a sturdy floor (flammable neighbours aside). - if below.sturdy_full >> 1 & 1 == 0 { - continue; - } - if let Some(fire) = self.pack.assets.registry.default_state(name) { + // BaseFireBlock.getState and FireBlock/SoulFireBlock.canSurvive. + let at = BlockPos::new(p[0], p[1], p[2]); + let fire = self.with_level(|b, level, ticks| { + let fire = b.fire_state_for(level, ticks, at); + b.can_survive(level, ticks, at, fire).then_some(fire) + }); + if let Some(fire) = fire { let _ = self.level_set(p, fire); } } @@ -219,7 +212,10 @@ impl Game<'_> { pitch, ); if !b.visual_only { - self.bolt_fire(b.at, 4); + // Only Normal and Hard start fires with the strike itself. + if self.ui.difficulty >= 2 { + self.bolt_fire(b.at, 4); + } self.strike_rod(b.at); } } From 7abb092089d5e2008234673454a50f393e26bbc6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:30:34 +0100 Subject: [PATCH 15/31] Wire fire burnout, difficulty and spread radius into the fire tick --- crates/horizon-client/src/biome.rs | 6 ++++ crates/horizon-client/src/game.rs | 48 ++++++++++++++++++++++++++ crates/horizon-client/src/game/chat.rs | 1 + crates/horizon-world/src/level/mod.rs | 8 +++++ crates/horizon-world/src/level/tick.rs | 5 ++- 5 files changed, 65 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 63ad004d4..c8c15e44e 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -28,6 +28,9 @@ pub struct BiomeInfo { pub spawn_costs: HashMap, /// The `gameplay/creature_world_gen_spawn_probability` attribute. pub creature_probability: f32, + /// The `gameplay/increased_fire_burnout` attribute (jungles, swamps, peaks, + /// mushroom fields). + pub increased_fire_burnout: bool, pub name: String, pub temperature: f32, pub downfall: f32, @@ -128,6 +131,9 @@ impl Biomes { attributes["minecraft:gameplay/creature_world_gen_spawn_probability"] .as_f64() .unwrap_or(0.1) as f32, + increased_fire_burnout: attributes["minecraft:gameplay/increased_fire_burnout"] + .as_bool() + .unwrap_or(false), temperature, downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..b3e379e02 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -552,6 +552,11 @@ struct GameLevel<'w> { loot: Option>, registry: &'static horizon_world::registry::BlockRegistry, rules: horizon_world::level::GameRules, + /// `Difficulty.getId()` (peaceful 0 .. hard 3). + difficulty: i32, + /// The feet of the players who keep fire spreading around them: the local + /// player and the LAN guests in this level, spectators aside. + fire_players: Vec<[f64; 3]>, /// Block loot random sequences (`ServerLevel.getRandomSequence`). rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, pending: &'w mut spill::Pending, @@ -715,6 +720,34 @@ impl LevelAccess for GameLevel<'_> { fn game_rules(&self) -> horizon_world::level::GameRules { self.rules } + fn difficulty(&self) -> i32 { + self.difficulty + } + /// `ServerLevel.canSpreadFireAround`: a player (not a spectator) closer + /// than the `fire_spread_radius_around_player` rule to the block's corner + /// (`ChunkMap.anyPlayerCloseEnoughTo`); -1 spreads everywhere. + fn can_spread_fire_around(&self, pos: BlockPos) -> bool { + let radius = self.rules.fire_spread_radius_around_player; + radius == -1 + || self.fire_players.iter().any(|p| { + let d = [ + p[0] - f64::from(pos.x), + p[1] - f64::from(pos.y), + p[2] - f64::from(pos.z), + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(radius) * f64::from(radius) + }) + } + fn increased_fire_burnout(&self, pos: BlockPos) -> bool { + self.world + .chunks + .get(&(pos.x >> 4, pos.z >> 4)) + .is_some_and(|chunk| { + self.biomes + .get(chunk.biome(pos.x, pos.y, pos.z)) + .increased_fire_burnout + }) + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.world.block(pos.x, pos.y, pos.z) } @@ -2454,6 +2487,19 @@ impl Game<'_> { Dim::End => LevelDimension::End, }; let rules = self.level_rules(); + let fire_players: Vec<[f64; 3]> = self + .player + .iter() + .filter(|_| !spectator) + .map(|p| [p.position.x, p.position.y, p.position.z]) + .chain(self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && !g.spectator()) + .map(|g| g.position) + })) + .collect(); let blockers = Blockers { mobs: &self.mobs, armor_stands: &self.armor_stands, @@ -2484,6 +2530,8 @@ impl Game<'_> { loot: horizon_client::structure_blocks::loot_data(&self.options.resources), registry: self.pack.assets.registry, rules, + difficulty: i32::from(self.ui.difficulty), + fire_players, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, spill: &mut self.spill, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index de5bbf116..fa108c723 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -778,6 +778,7 @@ impl Game<'_> { max_snow_accumulation_height: r.int("max_snow_accumulation_height"), spawn_mobs: r.bool("spawn_mobs"), spawn_monsters: r.bool("spawn_monsters"), + fire_spread_radius_around_player: r.int("fire_spread_radius_around_player"), } } /// Apply rules mirrored in other state (natural regeneration, difficulty). diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3831efbd6..bdc1562f9 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -180,6 +180,8 @@ pub struct GameRules { pub max_snow_accumulation_height: i32, pub spawn_mobs: bool, pub spawn_monsters: bool, + /// `fire_spread_radius_around_player`: -1 spreads everywhere. + pub fire_spread_radius_around_player: i32, } impl Default for GameRules { fn default() -> Self { @@ -192,6 +194,7 @@ impl Default for GameRules { max_snow_accumulation_height: 1, spawn_mobs: true, spawn_monsters: true, + fire_spread_radius_around_player: 128, } } } @@ -342,6 +345,11 @@ pub trait LevelAccess { fn can_spread_fire_around(&self, _pos: BlockPos) -> bool { true } + /// The `INCREASED_FIRE_BURNOUT` environment attribute at `pos` (a biome + /// attribute). + fn increased_fire_burnout(&self, _pos: BlockPos) -> bool { + false + } /// `Level.isUnobstructed(state, pos, context)`: whether the state's /// collision shape at `pos` would intersect an entity. fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool { diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 29f53e053..25e2a19d3 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -565,9 +565,8 @@ impl Sim<'_, L> { return; } } - // FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute - // (jungles, swamps, peaks, mushroom fields); Horizon doesn't yet. - let burnout = false; + // FireBlock.tick: the INCREASED_FIRE_BURNOUT environment attribute. + let burnout = self.level.increased_fire_burnout(pos); let extra = if burnout { -50 } else { 0 }; for (direction, chance) in [ (Direction::East, 300), From 199178907cf702a2949fb9494c40cf1e3c16c3f6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:30:49 +0100 Subject: [PATCH 16/31] Shovels put out a lit campfire --- crates/horizon-client/src/animate_tick.rs | 23 ++++++-- crates/horizon-client/src/game.rs | 5 ++ .../horizon-client/src/game/campfire_douse.rs | 53 +++++++++++++++++++ 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/campfire_douse.rs diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 48e8f16f4..7cf96d9df 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -1157,13 +1157,19 @@ pub fn campfire_particles<'a>( if r.next_float() < 0.11 { let count = next_int(r, 2) + 2; for _ in 0..count { - make_campfire_smoke(engine, pos, signal); + make_campfire_smoke(engine, pos, signal, false); } } } } -/// `CampfireBlock.makeParticles` (always visible, overriding the limiter). -pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) { +/// `CampfireBlock.makeParticles` (always visible, overriding the limiter); +/// `smoking` adds the plain smoke puff at the logs. +pub fn make_campfire_smoke( + engine: &mut ParticleEngine, + pos: [i32; 3], + signal: bool, + smoking: bool, +) { let r = engine.random(); let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 }; let dx = r.next_double() / 3.0; @@ -1177,6 +1183,17 @@ pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: b T::CampfireCosySmoke }; engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]); + if smoking { + let r = engine.random(); + let dx = r.next_double() / 4.0 * sign(r); + let dz = r.next_double() / 4.0 * sign(r); + let at = [ + f64::from(pos[0]) + 0.5 + dx, + f64::from(pos[1]) + 0.4, + f64::from(pos[2]) + 0.5 + dz, + ]; + engine.create(&ParticleOptions::simple(T::Smoke), at, [0.0, 0.005, 0.0]); + } } #[cfg(test)] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..7f5f77020 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -18,6 +18,7 @@ mod boats; mod books; mod bossbars; mod breezes; +mod campfire_douse; mod cartography; mod chat; mod client_ambient; @@ -3538,6 +3539,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_campfire_douse(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); diff --git a/crates/horizon-client/src/game/campfire_douse.rs b/crates/horizon-client/src/game/campfire_douse.rs new file mode 100644 index 000000000..04accb2d3 --- /dev/null +++ b/crates/horizon-client/src/game/campfire_douse.rs @@ -0,0 +1,53 @@ +//! `CampfireBlock.useItemOn`: an item in `#minecraft:douses_campfires` (the +//! shovels) put on a lit campfire puts it out. +use super::Game; +use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack}; + +impl Game<'_> { + /// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block + /// at `pos` clicked: true when it doused a lit campfire (SUCCESS). + pub(super) fn use_campfire_douse( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + ) -> Result { + let Some(tool) = held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:douses_campfires") + .is_some_and(|members| members.contains(&*s.item)) + }) else { + return Ok(false); + }; + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire")) + .filter(|s| s.properties.get("lit").map(String::as_str) == Some("true")) + .cloned() + else { + return Ok(false); + }; + // Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player. + self.level_event_at(1009, pos, 0); + // CampfireBlock.douse: the acting client's own smoke (twenty puffs), + // then the block change game event from the player. + if self.lan_acting.is_none() { + let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true"); + for _ in 0..20 { + make_campfire_smoke(&mut self.particles, pos, signal, true); + } + } + self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), None); + state.properties.insert("lit".into(), "false".into()); + if let Ok(unlit) = registry.resolve(&state) { + self.level_set(pos, unlit)?; + } + let used = tool.clone(); + self.damage_held(1); + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, &used); + Ok(true) + } +} From b1136ac287648375239b1813a1fc42303c235afc Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:30:54 +0000 Subject: [PATCH 17/31] Keep forced server levels ticking without players Fixes #1525. Respect forced tickets when scheduling levels and bound playerless integrated-server ticks to their ticket sources. Co-Authored-By: Codex (GPT-6.1 Sol) --- crates/horizon-client/src/game.rs | 17 ++++---- crates/horizon-client/src/game/levels.rs | 22 +++++++--- tools/lan_e2e.py | 53 ++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..2cc892d8d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2551,14 +2551,15 @@ impl Game<'_> { (p.position.z.floor() as i32) >> 4, )); } - let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| { - horizon_client::ticket_levels::Sources { - players, - forced: self.streaming.forced.iter().copied().collect(), - view_distance: self.settings.render_distance.clamp(2, 32), - simulation_distance: self.settings.simulation_distance.max(2), - } - }); + let sources = + (!self.options.execution_role.is_client() || !players.is_empty()).then(|| { + horizon_client::ticket_levels::Sources { + players, + forced: self.streaming.forced.iter().copied().collect(), + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), + } + }); self.tickets.update(sources); } /// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index bfc739cee..f68c52d87 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -3,8 +3,8 @@ //! The game's tick code reads one level: the one in place, held in `Game`'s //! own fields (the world, its streaming and save, block ticks, entities). //! A server (the dedicated server and single player's server thread) keeps -//! the other dimensions' levels here and ticks each one that has players by -//! swapping it into place (`enter_level`), the way `as_guest` swaps a player +//! the other dimensions' levels here and ticks each one with players or forced +//! chunks by swapping it into place (`enter_level`), the way `as_guest` swaps a player //! in, so the tick code runs unchanged, one level at a time. The in-frame //! game holds one level, which follows its player (`enter_dimension`). //! @@ -290,8 +290,8 @@ impl Game<'_> { } /// One server tick (`MinecraftServer.tickServer`): each level with - /// players in turn (`tickChildren`), its chunks streamed and loaded and - /// its world ticked. The first pass reads the network and runs the + /// players or forced chunks in turn (`tickChildren`), its chunks streamed + /// and loaded and its world ticked. The first pass reads the network and runs the /// tick's shared parts (the clock, the weather, functions, the autosave); /// the next ones only their level. While `paused`, only the connections /// run. @@ -393,7 +393,7 @@ impl Game<'_> { /// The levels this server tick runs, in `MinecraftServer.levels` order /// (the Overworld, the Nether, the End): every level with a player in - /// it or a `/pregen` task, or the Overworld while nobody is online. + /// it, forced chunks or a `/pregen` task, or the Overworld while idle. pub(super) fn levels_to_tick(&self) -> Vec { let guests = self .lan @@ -402,7 +402,17 @@ impl Game<'_> { let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] .into_iter() .filter(|d| { - guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d) + let forced = if *d == self.dim { + !self.streaming.forced.is_empty() + } else { + self.levels + .parked + .get(d) + .is_some_and(|p| !p.streaming.forced.is_empty()) + }; + guests.iter().any(|g| g.dimension == d.id()) + || forced + || self.pregen_level() == Some(*d) }) .collect(); if dims.is_empty() { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 6dabe6dd7..958950ee5 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6955,5 +6955,58 @@ CHECKS += ['sonic'] CHECK_FNS['sonic'] = check_sonic +def check_forced_levels(host, guest, out): + """#1525: forced block/entity ticks outlive the last player and the 300-tick idle timeout. + + Also keep a resident, unforced furnace outside the forced ticket's neighbour ring: scheduling + a playerless integrated-server level must not enable the fixtures' tick-everywhere fallback. + """ + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + start = pos_of(guest) + results = {} + guest('command', command='gamemode creative') + try: + for dimension in (NETHER, END): + into_level(guest, dimension, 8, 100, 8) + host('command', command='tick freeze') + furnace = ('minecraft:furnace{Items:[{Slot:0b,id:"minecraft:raw_iron",count:1},' + '{Slot:1b,id:"minecraft:coal",count:1}],cooking_total_time:200,' + 'cooking_time_spent:0}') + for x in (8, 56): + guest('command', command=f'setblock {x} 100 8 {furnace}') + server_reply(guest, f'execute if data block {x} 100 8 ' + 'Items[{Slot:0b,id:"minecraft:raw_iron"}] ' + 'run say forced-input-ready', 'forced-input-ready') + guest('command', command='forceload add 8 8') + guest('command', command='summon minecraft:armor_stand 8.5 104 8.5 {Tags:["forced_tick"]}') + guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}') + wait_dimension(guest, OVERWORLD, 400) + host('command', command='tick step 450') + host.wait(500) + prefix = f'execute in {dimension} ' + results[dimension] = server_reply( + host, prefix + 'if data block 8 100 8 Items[{Slot:2b,id:"minecraft:iron_ingot"}] ' + 'if data block 56 100 8 {cooking_time_spent:0} ' + 'if data block 56 100 8 Items[{Slot:0b,id:"minecraft:raw_iron"}] ' + 'if data entity @e[tag=forced_tick,limit=1] {Pos:[8.5d,101.0d,8.5d]} run say forced-level-pass', + 'forced-level-pass') + assert dims(host, guest) == (OVERWORLD, OVERWORLD), dims(host, guest) + host('command', command=prefix + 'run forceload remove 8 8') + host('command', command=prefix + 'run kill @e[tag=forced_tick]') + host('command', command='tick unfreeze') + finally: + host('command', command='tick unfreeze') + for dimension in (NETHER, END): + host('command', command=f'execute in {dimension} run forceload remove 8 8') + guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}') + guest('command', command='gamemode survival') + return results + + +CHECKS += ['forced-levels'] +CHECK_FNS['forced-levels'] = check_forced_levels + + if __name__ == '__main__': main() From fd1d857f1ba2485b468b8bfcdf45e79ce7517d50 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:32:02 +0100 Subject: [PATCH 18/31] Hoglins keep away from warped fungus, portals and respawn anchors Hoglins now sense the nearest block from the hoglin repellents tag within 8 blocks sideways and 4 up or down. While one is near they become passive for 200 ticks (the attack target is dropped and no new one is picked), walk away from it, and avoid picking random walk spots within 8 blocks of it. Being hit ends the passive state. --- crates/horizon-client/src/mobs.rs | 3 + crates/horizon-client/src/mobs/ai.rs | 14 ++++ crates/horizon-client/src/mobs/piglin.rs | 86 +++++++++++++++++++++++- crates/horizon-client/src/mobs/world.rs | 29 ++++++++ 4 files changed, 129 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..bf42bc587 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -709,6 +709,9 @@ pub struct Extra { /// A copper golem's `openedChestPos`. pub opened_chest: Option<[i32; 3]>, pub point: Option<[f64; 3]>, + /// `NEAREST_REPELLENT`: the nearest repelling block a hoglin or piglin + /// sensed, looked up every 20 ticks. + pub repellent: Option<[i32; 3]>, pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..2676c3a37 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1242,6 +1242,20 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if m.species() == Species::Strider { return super::strider::walk_target_value(m, w, p); } + // Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best. + if m.species() == Species::Hoglin { + let near = m.extra.repellent.is_some_and(|r| { + let d = |i: usize| i64::from(r[i] - p[i]); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < 64 + }); + return if near { + -1.0 + } else if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:crimson_nylium" { + 10.0 + } else { + 0.0 + }; + } // Bee.getWalkTargetValue: any air block. if m.species() == Species::Bee { return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) { diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 410364097..155d53d2f 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -9,7 +9,7 @@ use super::{ NearestTarget, Prey, RandomLookAround, Stroll, goal_clone, }, }; -use horizon_core::geometry::trig::Mth; +use horizon_core::geometry::{Vec3, trig::Mth}; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -83,12 +83,16 @@ pub fn register_hoglin(m: &mut Mob) { g.add(1, BabyPanic(super::goals::Panic::new(1.25))); g.add(2, MeleeAttack::new(1.0, true)); g.add(3, super::goals::Breed::new(1.0)); + g.add(3, HoglinAvoidRepellent); g.add(4, super::goals::FollowParent::new(1.1)); g.add(5, Stroll::avoiding_water(0.4)); g.add(6, LookAtPlayer::new(8.0)); m.ai.targets.add(1, HurtByTarget::new().alert()); - m.ai.targets - .add(2, NearestTarget::player(true).when(|m, _| !m.is_baby())); + // `HoglinAi.findNearestValidAttackTarget`: nothing while pacified. + m.ai.targets.add( + 2, + NearestTarget::player(true).when(|m, _| !m.is_baby() && m.extra.ints[0] <= 0), + ); } pub fn register_zoglin(m: &mut Mob) { let g = &mut m.ai.goals; @@ -108,6 +112,49 @@ pub fn register_zoglin(m: &mut Mob) { .interval(10), ); } +/// `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, true)` of the hoglin's +/// idle activity: closer than 8 blocks to a repellent, walk away from it. +#[derive(Clone, Debug)] +struct HoglinAvoidRepellent; +impl Goal for HoglinAvoidRepellent { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(r) = m.extra.repellent else { + return false; + }; + // Vec3.atBottomCenterOf. + let avoid = [ + f64::from(r[0]) + 0.5, + f64::from(r[1]), + f64::from(r[2]) + 0.5, + ]; + if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 { + return false; + } + for _ in 0..10 { + if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) { + let at = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + m.ai.pending_path = m.create_path_to(cx.w, at, 0); + return m.ai.pending_path.is_some(); + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, 1.0); + } +} /// Baby hoglins flee what hurts them; adults stand their ground. #[derive(Clone, Debug)] struct BabyPanic(super::goals::Panic); @@ -165,12 +212,45 @@ impl Goal for GoToWantedItem { m.extra.point = None; } } +/// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents` +/// block within 8 blocks sideways and 4 up or down. +fn find_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { + let tag = w.block_tags.get("minecraft:hoglin_repellents")?; + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + w.nearest_block(at, 8, 4, |_, name| tag.contains(name)) +} +/// The hoglin's repellent memories: the sensor (every 20 ticks), the end of +/// `PACIFIED` (`ints[0]`), a hit ending it (`HoglinAi.wasHurtBy`, `ints[1]` +/// remembers the hit seen) and `BecomePassiveIfMemoryPresent(NEAREST_REPELLENT, 200)`. +fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { + if m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } + if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.ints[1] { + m.extra.ints[1] = m.ai.last_hurt_by_time; + m.extra.ints[0] = 0; + } + if m.age.wrapping_add(m.id) % 20 == 0 { + m.extra.repellent = find_repellent(m, w); + } + if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { + m.extra.ints[0] = 200; + m.ai.target = None; + } +} /// Per-tick piglin and hoglin state: admiring, anger, zombification and the /// hoglin attack animation. Returns a conversion when it happens. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.extra.anim_ticks > 0 { m.extra.anim_ticks -= 1; } + if m.species() == Species::Hoglin && m.alive() { + hoglin_repellent(m, w); + } if m.extra.anger > 0 { m.extra.anger -= 1; if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) { diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 7836a49ef..aa665decc 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -65,6 +65,35 @@ impl MobWorld<'_> { pub fn has_tag(&self, tag: &str, block: &str) -> bool { self.block_tags.get(tag).is_some_and(|s| s.contains(block)) } + /// `findBlocksInBoxByManhattanDistance(at, range_xz, range_y).filterState(..).findFirst()`: + /// the first block `matches` accepts (given its position and name), going + /// out from `at` by Manhattan distance as `BlockPos.withinBoxByManhattanDistance` does. + pub fn nearest_block( + &self, + at: [i32; 3], + range_xz: i32, + range_y: i32, + matches: impl Fn([i32; 3], &str) -> bool, + ) -> Option<[i32; 3]> { + // Visiting order: distance, then x, then y, then +z before -z. + let mut best: Option<((i32, i32, i32, bool), [i32; 3])> = None; + for dx in -range_xz..=range_xz { + for dy in -range_y..=range_y { + for dz in -range_xz..=range_xz { + let key = (dx.abs() + dy.abs() + dz.abs(), dx, dy, dz < 0); + if best.is_some_and(|(k, _)| k <= key) { + continue; + } + let p = [at[0] + dx, at[1] + dy, at[2] + dz]; + let state = self.world.block(p[0], p[1], p[2]); + if !self.facts.is_air(state) && matches(p, &self.facts.get(state).name) { + best = Some((key, p)); + } + } + } + } + best.map(|(_, p)| p) + } /// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss. pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool { let mut scene = SceneCollisions { From 091a98656ea98e1869b66ab9192075bdbadc4a29 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:32:46 +0100 Subject: [PATCH 19/31] Dragon: find healing crystals in its grown box and cap healing at max The search now uses the dragon's 16 by 8 box grown by 32 blocks like EnderDragon.checkCrystals, and healing no longer goes above max health. --- crates/horizon-client/src/game/dragon.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index f28049fd5..4bb7993d3 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1685,21 +1685,31 @@ impl Game<'_> { .play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch); } } - // checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32. + // checkCrystals: heal 1 every 10 ticks from the nearest crystal, found + // among those touching the dragon's box grown by 32. let d = self.dragon.as_mut().expect("dragon"); if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH { - d.health += 1.0; + // LivingEntity.setHealth clamps to the maximum. + d.health = (d.health + 1.0).min(MAX_HEALTH); } if d.random.next_int_bound(10).unwrap_or(1) == 0 { let p = d.position; + // The dragon's 16 by 8 box. + let reach = Aabb::new( + Vec3::new(p.x - 8.0, p.y, p.z - 8.0), + Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0), + ) + .inflate(Vec3::new(32.0, 32.0, 32.0)); d.nearest_crystal = self .crystals .iter() .enumerate() .filter(|(_, c)| { - (c.position.x - p.x).abs() <= 32.0 - && (c.position.y - p.y).abs() <= 32.0 - && (c.position.z - p.z).abs() <= 32.0 + // An end crystal's 2 by 2 box. + reach.intersects(Aabb::new( + Vec3::new(c.position.x - 1.0, c.position.y, c.position.z - 1.0), + Vec3::new(c.position.x + 1.0, c.position.y + 2.0, c.position.z + 1.0), + )) }) .min_by(|a, b| { let da = (a.1.position.x - p.x).powi(2) From 6e0a49029fb4b28465bf8256bed71e44448643e3 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:39:51 +0000 Subject: [PATCH 20/31] Keep block-breaking cracks aligned between stages Restore integer atlas origins and sample local texel centers before nearest filtering. Cover the packed stage origins with a GPU sampling regression. Fixes #1882. Co-Authored-By: Codex GPT-6.1 Sol --- crates/horizon-client/src/entity.wgsl | 13 +- crates/horizon-client/src/gfx.rs | 2 + .../horizon-client/src/gfx/crumbling_tests.rs | 191 ++++++++++++++++++ 3 files changed, 205 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/gfx/crumbling_tests.rs diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2e865dfb1..79e11719f 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -166,12 +166,23 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { if d >= end { return 1.0; } return (d - start) / (end - start); } +// CRUMBLING_UV_BEGIN +fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, dimensions: vec2) -> vec2 { + let size = vec2(dimensions); + // Undo stage_light's 16-bit quantization before adding local texels. Otherwise + // different stages can fall on opposite sides of a nearest-sampling boundary. + let origin = round(packed_origin * size); + let extent = max(round(sprite_size * size), vec2(1.0)); + let local = min(floor(fract(uv) * extent), extent - vec2(1.0)); + return (origin + local + vec2(0.5)) / size; +} +// CRUMBLING_UV_END @fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). - uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; + uv = crumbling_uv(in.uv, in.wrap, globals.crumbling_sprite.zw, textureDimensions(atlas)); } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index ca308060b..660bfb2ad 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -32,6 +32,8 @@ fn entity_shader() -> String { crate::overlay::wgsl_constants() + include_str!("entity.wgsl") } +#[cfg(test)] +mod crumbling_tests; mod entity_batch; mod weather; use entity_batch::EntityBatch; diff --git a/crates/horizon-client/src/gfx/crumbling_tests.rs b/crates/horizon-client/src/gfx/crumbling_tests.rs new file mode 100644 index 000000000..620a57cf9 --- /dev/null +++ b/crates/horizon-client/src/gfx/crumbling_tests.rs @@ -0,0 +1,191 @@ +use wgpu::util::DeviceExt; + +/// Sample the production WGSL with the production nearest/no-mipmap atlas sampler. +#[test] +#[ignore = "requires a Vulkan/Metal/DX12 adapter"] +fn crack_samples_stay_aligned_between_stages() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) + .unwrap(); + eprintln!("crack sampling adapter: {:?}", adapter.get_info()); + let (device, queue) = + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap(); + #[repr(C)] + #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] + struct Case { + uv: [f32; 2], + stage: u32, + extent: u32, + } + let mut cases = Vec::new(); + let mut expected = Vec::<[u32; 2]>::new(); + // Include exact texel boundaries, their neighbours, negative projected UVs, + // wrapping and the far sprite edge. Origins straddle the packing error's sign change. + for extent in [16, 32] { + for x in [32, 2080, 4064] { + for y in [0, 32] { + for i in -32..=32 { + for delta in [-0.0001, 0.0, 0.0001] { + let uv = [i as f32 / 16.0 + delta, 0.5 - delta]; + cases.push(Case { + uv, + stage: crate::breaking::stage_light([ + x as f32 / 4096.0, + y as f32 / 64.0, + ]), + extent, + }); + expected.push(uv.map(|v| { + (((v - v.floor()) * extent as f32).floor() as u32).min(extent - 1) + })); + } + } + } + } + } + let math = include_str!("../entity.wgsl") + .split("// CRUMBLING_UV_BEGIN") + .nth(1) + .unwrap() + .split("// CRUMBLING_UV_END") + .next() + .unwrap(); + let source = format!( + "{math}\n{}", + r#" +struct Case { uv: vec2, stage: u32, extent: u32 } +@group(0) @binding(0) var cases: array; +@group(0) @binding(1) var results: array>; +@group(0) @binding(2) var atlas: texture_2d; +@group(0) @binding(3) var atlas_sampler: sampler; +@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + if id.x >= arrayLength(&cases) { return; } + let c = cases[id.x]; + let origin = vec2(f32(c.stage & 65535u), f32(c.stage >> 16u)) / 65535.0; + let dimensions = textureDimensions(atlas); + let uv = crumbling_uv(c.uv, origin, vec2(f32(c.extent)) / vec2(dimensions), dimensions); + // Keep the old addressing as a control: the fixture must reproduce its stage jitter. + let old_uv = origin + fract(c.uv) * vec2(f32(c.extent)) / vec2(dimensions); + results[id.x] = vec4( + vec2(round(textureSampleLevel(atlas, atlas_sampler, uv, 0.0).rg * 255.0)), + vec2(round(textureSampleLevel(atlas, atlas_sampler, old_uv, 0.0).rg * 255.0))); +}"# + ); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Crack sampling regression"), + source: wgpu::ShaderSource::Wgsl(source.into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &shader, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + // Every sprite repeats the same coordinate pattern, so moving a stage's + // atlas origin must leave every sampled local texel unchanged. + let pixels: Vec = (0..64) + .flat_map(|y| (0..4096).flat_map(move |x| [(x % 32) as u8, (y % 32) as u8, 0, 255])) + .collect(); + let atlas = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 4096, + height: 64, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &pixels, + ); + let view = atlas.create_view(&Default::default()); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default()); + let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(&cases), + usage: wgpu::BufferUsages::STORAGE, + }); + let size = (expected.len() * 16) as u64; + let output = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: input.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: output.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &group, &[]); + pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1); + } + encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size); + queue.submit([encoder.finish()]); + let (tx, rx) = std::sync::mpsc::channel(); + readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + rx.recv().unwrap().unwrap(); + let mapped = readback.get_mapped_range(..).unwrap(); + let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped); + for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() { + assert_eq!( + &actual[..2], + expected, + "case {i}, uv={:?}, stage={}, extent={}", + cases[i].uv, + cases[i].stage, + cases[i].extent + ); + } + let old_mismatches = actual + .iter() + .zip(&expected) + .filter(|(a, e)| &a[2..] != e.as_slice()) + .count(); + assert!( + old_mismatches > 0, + "fixture must detect the original sampling bug" + ); + eprintln!( + "{} crack texture samples matched; old addressing mismatched {old_mismatches}", + cases.len() + ); +} From f0d2a2ae741f0319ff66e7e04cfb5dfdb13c2f54 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:02:43 +0100 Subject: [PATCH 21/31] Satisfy clippy --- crates/horizon-client/src/mobs/piglin.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 155d53d2f..6bf0aa096 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -234,7 +234,7 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.extra.ints[1] = m.ai.last_hurt_by_time; m.extra.ints[0] = 0; } - if m.age.wrapping_add(m.id) % 20 == 0 { + if m.age.wrapping_add(m.id).is_multiple_of(20) { m.extra.repellent = find_repellent(m, w); } if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { From 48811b12f1fc3146e74b7b45f01e6e92ae3a5ab2 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 14:54:31 +0100 Subject: [PATCH 22/31] Pistons animate their moves on the clients, as Java's do A remote client (single player's window on its server thread, a LAN guest, a dedicated server's client) never ran the client side of a piston's move: the block event reached block_entity_event, which has no piston ticker, so moving_piston blocks arrived with no moving block entity and pushed blocks teleported (#1704). Vanilla's runBlockEvents broadcasts a handled event to the clients, whose own level re-runs triggerEvent (PistonBaseBlock.moveBlocks) to build the PistonMovingBlockEntity it then ticks and renders interpolated. Do the same: - run_block_events emits a BlockEntityEvent for a handled event; the LAN and integrated hubs send it as ClientboundBlockEventPacket, before the tick's block changes, as vanilla's broadcast precedes ChunkHolder.broadcastChanges. - The remote client re-runs triggerEvent for pistons, note blocks and bells on its own level (dropResources stays server-side, as popResource checks !isClientSide), and ticks the resulting moving pistons each client tick so they animate and collide between the server's states. Block events a client-side move queues run right away, as ClientLevel.blockEvent does. Note blocks and bell rings reach the guests through the same packet, which they did not get before. Co-Authored-By: Devin --- crates/horizon-client/src/game.rs | 14 +- crates/horizon-client/src/game/lan.rs | 41 ++++-- crates/horizon-client/src/game/remote.rs | 41 ++++-- crates/horizon-world/src/level/mod.rs | 5 + crates/horizon-world/src/level/pistons.rs | 150 +++++++++++++++++++--- crates/horizon-world/src/level/tests.rs | 62 +++++++++ 6 files changed, 274 insertions(+), 39 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a29b497ce..834bcfbe1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -563,6 +563,9 @@ struct GameLevel<'w> { random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections, /// Players with each chest open (a trapped chest's signal). lid_openers: &'w HashMap<(i32, i32, i32), i32>, + /// `Level.isClientSide`: a client's copy of the level (a guest of a LAN + /// world, a window on its server thread, a dedicated server's client). + client_side: bool, } struct PlayerCollision { y: f64, @@ -652,6 +655,9 @@ impl GameLevel<'_> { } } impl LevelAccess for GameLevel<'_> { + fn is_client_side(&self) -> bool { + self.client_side + } fn world_surface(&self, x: i32, z: i32) -> i32 { self.world.world_surface(x, z, |s| self.facts.is_air(s)) } @@ -855,7 +861,12 @@ impl LevelAccess for GameLevel<'_> { fn emit(&mut self, event: LevelEvent) { match event { // Block.dropResources draws its loot and spots right away. - LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state), + // `popResource` only drops server-side (`!level.isClientSide`): + // a client's moveBlocks (a piston's block event) skips it. + LevelEvent::DropResources { pos, state } if !self.client_side => { + self.drop_resources_now(pos, state) + } + LevelEvent::DropResources { .. } => {} // Block.popResource of the block's own item (tall flowers, flower beds). LevelEvent::BlockEvent { pos, @@ -2492,6 +2503,7 @@ impl Game<'_> { tickets: self.tickets.levels(), random_tick_sections: &mut self.random_tick_sections, lid_openers: &self.lid_openers, + client_side: self.remote.is_some(), }; let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9f468db9f..c65a2bd8e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -923,6 +923,13 @@ impl Game<'_> { for m in &mut self.mobs { m.needs_sync = false; } + // `runBlockEvents`' broadcast precedes the tick's block changes + // (`ChunkHolder.broadcastChanges` in `tick_level` below): the + // guest re-runs a piston's `triggerEvent` while its level still + // has the blocks as they were before the move. + for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) { + host.hub.block_event(pos, b0, b1, state); + } let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { @@ -1156,17 +1163,29 @@ impl Game<'_> { return; } for e in events { - if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { - // The acting guest does not predict the egg's teleport - // particles, bone meal's growth, or anvil result sounds - // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { - None - } else { - self.lan_acting - }; - self.lan_events - .push((*id, [pos.x, pos.y, pos.z], *data, except)); + match e { + horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { + // The acting guest does not predict the egg's teleport + // particles, bone meal's growth, or anvil result sounds + // (these levelEvent calls name no excluded player). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + None + } else { + self.lan_acting + }; + self.lan_events + .push((*id, [pos.x, pos.y, pos.z], *data, except)); + } + // `ServerLevel.runBlockEvents` broadcasts a handled block + // event (`ClientboundBlockEventPacket`): the guest re-runs + // the block's `triggerEvent` — a piston's `moveBlocks` is + // what animates the move there. `state` is the block the + // event named, read before it ran (the packet's `block`). + horizon_world::level::LevelEvent::BlockEntityEvent { pos, state, a, b } => { + self.lan_block_events + .push(([pos.x, pos.y, pos.z], *a, *b, state.0)); + } + _ => {} } } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 857f955da..637e0c542 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1664,19 +1664,30 @@ impl Game<'_> { } } C::BlockChangedAck(p) => self.end_predictions(p.sequence), - // ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids, - // shulker boxes, bells) when the block is still the one it names. + // Level.blockEvent on the client level: the block's triggerEvent + // runs on the client's copy of whatever is at pos (a piston's + // moveBlocks builds the moving block entities it animates, a note + // block plays); what it doesn't handle reaches the client copy of + // the block entity (chest lids, shulker boxes). C::BlockEvent(p) => { - let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let block = &self.res.facts().get(state).name; - let named = self.remote.as_ref().and_then(|r| { - r.builtin - .get("minecraft:block")? - .name(p.block) - .map(str::to_owned) + let pos = horizon_core::position::BlockPos::new(p.pos[0], p.pos[1], p.pos[2]); + let triggered = self.with_level(|b, level, ticks| { + b.client_block_event(level, ticks, pos, i32::from(p.b0), i32::from(p.b1)) }); - if named.as_deref() == Some(&**block) { - self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + self.sync_moving_pistons(); + self.process_level_events()?; + if !triggered { + let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); + let block = &self.res.facts().get(state).name; + let named = self.remote.as_ref().and_then(|r| { + r.builtin + .get("minecraft:block")? + .name(p.block) + .map(str::to_owned) + }); + if named.as_deref() == Some(&**block) { + self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + } } } // ClientLevel.levelEvent: LevelEventHandler, as this client's own @@ -3108,8 +3119,14 @@ impl Game<'_> { self.border.tick(); self.player_border(); self.tick_remote_entities(running); - // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. + // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells, + // and the moving pistons a block event's client-side moveBlocks made + // (their progress advances between the server's block updates). self.tick_block_entity_anims(); + self.with_level(|b, level, ticks| { + b.client_tick_block_entities(level, ticks); + }); + self.sync_moving_pistons(); self.tick_hand(); self.tick_particles(); self.tick_client_ambient(); diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3831efbd6..d4af6fb9e 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -287,6 +287,11 @@ pub enum LevelEvent { /// The world as seen by block behaviour. Implemented by the game and tests. pub trait LevelAccess { + /// `Level.isClientSide`: this level is a client's copy (false on a + /// server, a host or the test harness). + fn is_client_side(&self) -> bool { + false + } /// `getBlockState`. Unloaded or out-of-bounds positions read as air. fn block_state(&self, pos: BlockPos) -> BlockStateId; /// Storage write (`LevelChunkSection.setBlockState`). Returns the previous diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 648d6d543..5a34433e1 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -27,6 +27,9 @@ pub struct MovingPiston { pub progress: f32, pub progress_o: f32, pub last_ticked: i64, + /// `PistonMovingBlockEntity.deathTicks`: on a client the entity waits + /// five ticks past progress 1.0 before placing the block itself. + pub death_ticks: i32, /// Identity of this block entity (a replaced entity is a new ticker). pub id: u64, } @@ -126,11 +129,8 @@ impl Sim<'_, L> { self.note_trigger_event(pos, state); true } else if data.is(super::classes::Class::Bell) { - // BellBlockEntity.triggerEvent handles event 1; the server - // broadcasts handled events to the clients. - if a == 1 { - self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); - } + // BellBlockEntity.triggerEvent handles event 1; the caller + // reports handled events (`runBlockEvents` broadcasts them). a == 1 } else { false @@ -164,7 +164,9 @@ impl Sim<'_, L> { let Some(piston) = self.moving_piston(pos) else { return; }; - if piston.progress_o >= 1.0 { + // finalTick: `progressO < 1.0 || level.isClientSide` — a client + // finishes its copy even at full progress. + if piston.progress_o >= 1.0 && !self.level.is_client_side() { return; } self.remove_moving_piston(pos); @@ -189,6 +191,20 @@ impl Sim<'_, L> { piston.last_ticked = self.level.game_time(); piston.progress_o = piston.progress; if piston.progress_o >= 1.0 { + if self.level.is_client_side() && piston.death_ticks < 5 { + // The client's copy waits for the server's state before + // placing the block itself (deathTicks < 5). + piston.death_ticks += 1; + if let Some(entry) = self + .ticks + .moving_pistons + .iter_mut() + .find(|(p, _)| *p == pos) + { + entry.1 = piston; + } + return; + } self.remove_moving_piston(pos); if b.is_block(self.state(pos), b.named.moving_piston) { let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos); @@ -527,6 +543,12 @@ impl Sim<'_, L> { for pos in to_destroy.iter().rev() { let state = self.state(*pos); self.drop_resources(state, *pos); + // The client's copy plays the destroy effect itself (the + // server sends no 2001 for piston moves). + let fire = b.is_block(state, b.named.fire) || b.is_block(state, b.named.soul_fire); + if !fire && self.level.is_client_side() { + self.level_event(2001, *pos, state.0 as i32); + } self.set_block(*pos, b.air(), 18); self.game_event(*pos, "minecraft:block_destroy"); to_update.push(state); @@ -551,6 +573,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -576,6 +599,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -624,13 +648,17 @@ impl Sim<'_, L> { let direction = b.facing(state); let extended_state = b.table.set_bool(state, p.extended, true); let sticky = self.is_sticky_piston(state); - let extend = self.piston_neighbor_signal(pos, direction); - if extend && (a == 1 || a == 2) { - self.set_block(pos, extended_state, 2); - return false; - } - if !extend && a == 0 { - return false; + // The signal re-check is server-only (`!level.isClientSide`): a + // client trusts the event as sent. + if !self.level.is_client_side() { + let extend = self.piston_neighbor_signal(pos, direction); + if extend && (a == 1 || a == 2) { + self.set_block(pos, extended_state, 2); + return false; + } + if !extend && a == 0 { + return false; + } } if a == 0 { if !self.piston_move_blocks(pos, direction, true, sticky) { @@ -664,6 +692,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -748,8 +777,18 @@ impl Behaviours { } let mut sim = self.sim(level, ticks); let state = sim.state(event.pos); - if self.block(state) == event.block { - sim.trigger_event(state, event.pos, event.param_a, event.param_b); + if self.block(state) == event.block + && sim.trigger_event(state, event.pos, event.param_a, event.param_b) + { + // ServerLevel.runBlockEvents broadcasts a handled event to + // the clients (`ClientboundBlockEventPacket`); their copy of + // the block re-runs `triggerEvent` (a piston's `moveBlocks`). + sim.emit(LevelEvent::BlockEntityEvent { + pos: event.pos, + state, + a: event.param_a, + b: event.param_b, + }); } } for event in reschedule { @@ -779,4 +818,85 @@ impl Behaviours { self.sim(level, ticks).moving_piston_tick(pos); } } + /// `ClientLevel.blockEvent`: the client re-runs the block's + /// `triggerEvent` on its own level (a piston's `moveBlocks` builds the + /// moving block entities it then animates) instead of waiting for the + /// server's states. No queue and no ticking-chunk gate: a client runs + /// the event where the packet lands. + pub fn client_block_event( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + a: i32, + b: i32, + ) -> bool { + let triggered = { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let triggered = sim.trigger_event(state, pos, a, b); + if triggered { + // The client's copy of a handled event reaches the client + // copy of the block entity (a bell's ring). + sim.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); + } + triggered + }; + self.client_drain_block_events(level, ticks); + triggered + } + /// `ClientLevel.tickBlockEntities` for moving pistons: the client copy of + /// [`Behaviours::tick_block_entities`], without the server's + /// ticking-chunk gate (a client ticks every loaded block entity). One + /// whose block was replaced is dropped (`TickingBlockEntity.isRemoved`). + pub fn client_tick_block_entities( + &self, + level: &mut L, + ticks: &mut Ticks, + ) { + let tickers: Vec<(BlockPos, u64)> = ticks + .moving_pistons + .iter() + .map(|(p, m)| (*p, m.id)) + .collect(); + for (pos, id) in tickers { + if !ticks + .moving_pistons + .iter() + .any(|(p, m)| *p == pos && m.id == id) + { + continue; + } + { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if sim.b.is_block(state, sim.b.named.moving_piston) { + sim.moving_piston_tick(pos); + } else { + sim.remove_moving_piston(pos); + } + } + self.client_drain_block_events(level, ticks); + } + } + /// Block events a client-side `triggerEvent` queued + /// (`PistonBaseBlock.checkIfExtend` in a neighbour update): a client + /// runs them as they come (`ClientLevel.blockEvent`), not in a tick pass. + fn client_drain_block_events(&self, level: &mut L, ticks: &mut Ticks) { + while let Some(event) = ticks.block_events.first().copied() { + ticks.block_events.remove(0); + let mut sim = self.sim(level, ticks); + let state = sim.state(event.pos); + if self.block(state) == event.block + && sim.trigger_event(state, event.pos, event.param_a, event.param_b) + { + sim.emit(LevelEvent::BlockEntityEvent { + pos: event.pos, + state, + a: event.param_a, + b: event.param_b, + }); + } + } + } } diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 8a4b6c34f..4777ec66e 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -919,6 +919,68 @@ fn pistons_push_and_sticky_pistons_pull() { assert_eq!(w.get(BlockPos::new(2, 1, 0)), air); } +/// `ServerLevel.runBlockEvents` reports a handled event for the clients +/// (`ClientboundBlockEventPacket`), carrying the block the event named. +#[test] +fn a_handled_block_event_reaches_the_clients() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + w.set(BlockPos::new(0, 1, 0), piston); + w.set(BlockPos::new(-1, 1, 0), block); + w.level.events.clear(); + w.full_tick(); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::BlockEntityEvent { + pos, + state, + a: 0, + .. + } if *pos == BlockPos::new(0, 1, 0) && *state == piston + ))); +} + +/// `ClientLevel.blockEvent`: the client re-runs `triggerEvent` on its own +/// level, which builds the moving block entities a piston's `moveBlocks` +/// makes, and ticks them to the placed block. +#[test] +fn a_client_replays_a_pistons_block_event() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("sticky_piston", &[("facing", "east")]); + let dirt = w.id("dirt", &[]); + let block = w.id("redstone_block", &[]); + w.put(BlockPos::new(0, 1, 0), piston); + w.put(BlockPos::new(1, 1, 0), dirt); + w.put(BlockPos::new(-1, 1, 0), block); + w.f.behaviours.client_block_event( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + 0, + Direction::East as i32, + ); + assert!( + w.ticks + .moving_pistons + .iter() + .any(|(p, _)| *p == BlockPos::new(2, 1, 0)) + ); + for _ in 0..3 { + w.level.time += 1; + w.f.behaviours + .client_tick_block_entities(&mut w.level, &mut w.ticks); + } + assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt); + assert_eq!( + w.name(BlockPos::new(1, 1, 0)), + "piston_head[facing=east,short=false,type=sticky]" + ); + assert!(w.ticks.moving_pistons.is_empty()); +} + #[test] fn pistons_pop_fragile_blocks_and_refuse_obsidian() { let mut w = world!(); From 545370b02370e6eab59fe6640d529f7a15379315 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:41:11 +0100 Subject: [PATCH 23/31] Key binds: press a shared default key once --- crates/horizon-client/src/keybinds.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 99eb5a15a..7575fb953 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -275,6 +275,20 @@ impl Default for KeyBinds { } } } +/// Each default key once, in order: two mappings that share a default key +/// (Advancements and the debug profiler both on L) are one press of it, not +/// two (the second would close the screen the first opened). Vanilla clicks +/// both mappings, but the profiler one only acts with F3 held. +fn distinct(keys: Vec) -> Vec { + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + if !out.contains(&k) { + out.push(k); + } + } + out +} + impl KeyBinds { pub fn get(&self, name: &str) -> &str { self.keys @@ -356,7 +370,7 @@ impl KeyBinds { }) .collect(); if !bound.is_empty() { - return bound; + return distinct(bound); } // An unbound key whose default meaning was moved elsewhere is inert. if MAPPINGS @@ -385,7 +399,7 @@ impl KeyBinds { }) .collect(); if !bound.is_empty() { - return bound; + return distinct(bound); } if MAPPINGS .iter() From 2394d6e7dc1ee0bcbf59c94fa9a37e7f3bf910f9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:14:21 +0100 Subject: [PATCH 24/31] Pistons: a client's replay starts no piston and plays no sound A client's copy of a block event (`client_block_event`) ran the server's neighbour logic: a block it moved could start another piston on the client alone (`PistonBaseBlock.checkIfExtend` is only called server-side), and the re-run's `playSound(null, ...)` played the piston and note sounds a second time next to the server's (`ClientLevel.playSeededSound` plays only for the local player as the excluded one). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 +++ crates/horizon-world/src/level/pistons.rs | 7 ++++- crates/horizon-world/src/level/tests.rs | 38 +++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 834bcfbe1..efc225d50 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -867,6 +867,10 @@ impl LevelAccess for GameLevel<'_> { self.drop_resources_now(pos, state) } LevelEvent::DropResources { .. } => {} + // `ClientLevel.playSeededSound` plays only when the excluded + // player is this client's own: the block's `playSound(null, ...)` + // (a piston's move, a note) reaches it from the server instead. + LevelEvent::Sound { .. } if self.client_side => {} // Block.popResource of the block's own item (tall flowers, flower beds). LevelEvent::BlockEvent { pos, diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 5a34433e1..45e469efd 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -257,8 +257,13 @@ impl Sim<'_, L> { direction != Direction::Down && self.has_signal(rel(up, direction), direction) }) } - /// `PistonBaseBlock.checkIfExtend`. + /// `PistonBaseBlock.checkIfExtend`, which `neighborChanged`, `onPlace` + /// and `setPlacedBy` call only server-side: a client moves its pistons on + /// the server's block events alone. pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) { + if self.level.is_client_side() { + return; + } let b = self.b; let direction = b.facing(state); let extend = self.piston_neighbor_signal(pos, direction); diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 4777ec66e..da75083d2 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -47,6 +47,8 @@ pub(crate) struct TestLevel { pub day_time: i64, pub events: Vec, pub block_light: HashMap, + /// `Level.isClientSide`. + pub client_side: bool, } impl TestLevel { fn new(b: &Behaviours) -> Self { @@ -58,10 +60,14 @@ impl TestLevel { day_time: 0, events: Vec::new(), block_light: HashMap::new(), + client_side: false, } } } impl LevelAccess for TestLevel { + fn is_client_side(&self) -> bool { + self.client_side + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.blocks.get(&pos).copied().unwrap_or(self.air) } @@ -981,6 +987,38 @@ fn a_client_replays_a_pistons_block_event() { assert!(w.ticks.moving_pistons.is_empty()); } +/// A client's copy of a move doesn't start the pistons the moved block +/// powers (`checkIfExtend` is server-only): their own block events come from +/// the server. +#[test] +fn a_client_replay_starts_no_other_piston() { + let mut w = world!(); + w.floor(0, 10, "stone"); + w.level.client_side = true; + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + let up = w.id("piston", &[("facing", "up")]); + w.put(BlockPos::new(0, 1, 0), piston); + w.put(BlockPos::new(1, 1, 0), block); + w.put(BlockPos::new(2, 2, 0), up); + w.f.behaviours.client_block_event( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + 0, + Direction::East as i32, + ); + for _ in 0..10 { + w.level.time += 1; + w.f.behaviours + .client_tick_block_entities(&mut w.level, &mut w.ticks); + } + assert_eq!(w.get(BlockPos::new(2, 1, 0)), block); + assert_eq!(w.get(BlockPos::new(2, 2, 0)), up); + assert!(w.ticks.moving_pistons.is_empty()); + assert!(w.ticks.block_events.is_empty()); +} + #[test] fn pistons_pop_fragile_blocks_and_refuse_obsidian() { let mut w = world!(); From 68aa70108f3c757bcef066c473645533d7e1d656 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:23:05 +0100 Subject: [PATCH 25/31] Piglin AI: name the hoglin repellent finder for its mob #2191 and #2192 each add a `find_repellent` to piglin.rs, one for hoglins and one for piglins; merged together they would collide. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/piglin.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 6bf0aa096..fff536932 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -214,7 +214,7 @@ impl Goal for GoToWantedItem { } /// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents` /// block within 8 blocks sideways and 4 up or down. -fn find_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { +fn find_hoglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { let tag = w.block_tags.get("minecraft:hoglin_repellents")?; let at = [ m.position.x.floor() as i32, @@ -235,7 +235,7 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.extra.ints[0] = 0; } if m.age.wrapping_add(m.id).is_multiple_of(20) { - m.extra.repellent = find_repellent(m, w); + m.extra.repellent = find_hoglin_repellent(m, w); } if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { m.extra.ints[0] = 200; From 0bd6a576a989be5a78ce7a8f5310efbe119610e7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:12:10 +0100 Subject: [PATCH 26/31] Tools: the ThinkPad no longer runs harnesses or builds; playhorizon is the Linux host Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 6 +++--- tools/ci/linux-runner.sh | 2 +- tools/parity_hosts.json | 14 +------------- tools/pr_ready.py | 6 ++---- 4 files changed, 7 insertions(+), 21 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 5eaac1a1d..27505d9de 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -13,7 +13,7 @@ python3 tools/parity.py --failed # the ones that failed last time python3 tools/parity.py --all # everything, from scratch: the audit (26 minutes on the Mac mini alone) python3 tools/parity.py --fresh food # don't reuse vanilla oracle results python3 tools/parity.py --repeat 3 food # run it three times; the runs must agree -python3 tools/parity.py --hosts macmini,thinkpad # with other machines (default: tools/parity_hosts.json's default list, empty) +python3 tools/parity.py --hosts macmini,playhorizon # with other machines (default: tools/parity_hosts.json's default list, empty) python3 tools/parity.py --list # what would run python3 tools/parity.py --status # last result of each harness python3 tools/parity.py --changed origin/main # those a branch's changes can affect (CI's parity job) @@ -40,9 +40,9 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder ### Other machines -Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. +Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 6. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. -Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop. +Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. ### Shards and Rust scopes diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh index 5a5e72697..293428da1 100755 --- a/tools/ci/linux-runner.sh +++ b/tools/ci/linux-runner.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # A Horizon CI runner (labels self-hosted, Linux, X64, horizon-game and the host's name) on a Linux machine of the -# maintainer's (NixOS: ludodesktop, ludothinkpad; Ubuntu: playhorizon, a partner's server), as a systemd user service +# maintainer's (NixOS: ludodesktop; Ubuntu: playhorizon, a partner's server), as a systemd user service # of the account that holds his Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that # machine, as that user: # diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index b98091f4f..f76a7f82c 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -28,19 +28,7 @@ "python": "python3.13", "jobs": 6, "nice": 10, - "note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the light Linux checks that used to go to the ThinkPad go here" - }, - "thinkpad": { - "ssh": "thinkpad", - "root": "code/horizon-parity", - "shell": "sh -c", - "jobs": 2, - "nice": 19, - "environment": { - "PARITY_BUILD_JOBS": "2" - }, - "note": "hosts the Claude account pool: two harnesses at most, at the lowest priority", - "setup": "export PKG_CONFIG_PATH=$HOME/code/horizon-parity/alsa-dev/lib/pkgconfig" + "note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)" } }, "local_only": { diff --git a/tools/pr_ready.py b/tools/pr_ready.py index df75025ed..5b1622e2e 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -46,12 +46,10 @@ from tools import parity, release_train # noqa: E402 RBUILD = Path.home() / "fleet" / "rbuild" LINE_LIMIT = 500 -# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad hosts -# the Claude account pool: three jobs at most. +# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad no +# longer builds (2026-10-26: it keeps the AI pool and a few services; Linux work goes to playhorizon's runner). HOST_SETUP = { "macmini": "source ~/.cargo/env; export PATH=/opt/homebrew/bin:$PATH CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-10}", - "thinkpad": 'export CARGO_BUILD_JOBS=3 PKG_CONFIG_PATH="$(ls -d /nix/store/*-alsa-lib-*-dev/lib/pkgconfig | tail -1):' - '$(ls -d /nix/store/*-systemd-*-dev/lib/pkgconfig | tail -1)"', "local": "", } # Hosts that hold the vanilla data, and how a run there gets it: CI's own runner scripts on the parity runner's From 0f22a274fa302c60dd9667b101bd201fb79b7d1d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:44:05 +0100 Subject: [PATCH 27/31] test_remote_motion: stub what remote_motion reaches on main remote_motion now also hands motion to the dragon, its fireballs, thrown potions and eyes of ender; the extracted fixture needs those to compile. Co-Authored-By: Claude Opus 5.5 --- tests/test_remote_motion.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py index da059c60b..b00e5f0a9 100644 --- a/tests/test_remote_motion.py +++ b/tests/test_remote_motion.py @@ -27,11 +27,19 @@ struct Remote { pending_items: HashMap } #[derive(Default)] struct Creatures { projectiles: Vec } #[derive(Default)] +struct Potions; +impl Potions { fn remote_thrown_motion(&mut self, _id: u32, _v: Vec3) -> bool { false } } +#[derive(Default)] +struct End; +impl End { fn remote_eye_motion(&mut self, _id: u32, _v: [f64; 3]) {} } +#[derive(Default)] struct Game { mobs: Vec, dropped: Vec, falling: Vec, tnts: Vec, - creatures: Creatures, remote: Option, + creatures: Creatures, dragon_fireballs: Vec, remote: Option, + potions: Potions, end: End, } impl Game { +fn remote_dragon_motion(&mut self, _id: i32, _velocity: [f64; 3]) {} METHOD } fn main() { From d01a621fec1f4ac79f9661cd9b741b0d5bc08719 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:46:06 +0100 Subject: [PATCH 28/31] tests: two parity-runner tests pass on macOS OracleReuseTests ran the shim through `#!/usr/bin/env python3` with a PATH whose Python folder is Homebrew's, which names it only python3.13: the shim wasn't found (127). The test now gives that PATH a python3 of its own. test_report_rejects_sources_changed_during_a_run compared a resolved source path with an unresolved temp root, and macOS's /var is /private/var. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_runner.py | 6 +++++- tests/test_rust_parity.py | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index a85f1e969..518f23ba4 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -259,7 +259,11 @@ class OracleReuseTests(unittest.TestCase): self.input, self.output = root / "work" / "in.txt", root / "work" / "out.txt" self.input.parent.mkdir() self.input.write_text("a") - python = Path(sys.executable).parent + # The shim starts with `#!/usr/bin/env python3`, and a Python's own folder may name it only + # python3.13 (Homebrew's): a python3 of its own keeps the PATH below enough. + python = root / "python" + python.mkdir() + (python / "python3").symlink_to(sys.executable) self.env = dict(os.environ, PATH=f"{self.shim}:{self.bin}:{python}", PARITY_SHIM_REAL_PATH=str(self.bin), PARITY_SHIM_CACHE=str(root / "cache")) self.subprocess = subprocess diff --git a/tests/test_rust_parity.py b/tests/test_rust_parity.py index b14723c16..68a68d6e1 100644 --- a/tests/test_rust_parity.py +++ b/tests/test_rust_parity.py @@ -10,7 +10,9 @@ from tools import test_rust_parity as parity class ParityRunnerTests(unittest.TestCase): def test_report_rejects_sources_changed_during_a_run(self): with tempfile.TemporaryDirectory() as temp: - root = Path(temp) + # Resolved, as source_hashes resolves the sources: macOS's temp folder is a symlink + # (/var -> /private/var). + root = Path(temp).resolve() source = root / "source.rs" source.write_text("before") with mock.patch.object(parity.lab, "ROOT", root): From fbbed63f04094038e076f127c5995b72f2b85d31 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:02:34 +0100 Subject: [PATCH 29/31] setblock and data keep a container's loot table A command's tag went through decode_block_entity, which has nowhere to put LootTable, so `setblock ... chest{LootTable:...}` made an empty chest (`data get` showed `Items: []`). An empty container given a LootTable is now rolled as a loaded chunk's are, and the roll is kept with its chunk (RolledLoot), so it saves, and `data get` shows, LootTable and LootTableSeed until its items change (tryLoadLootTable / trySaveLootTable). `data merge` and `data modify` go through the same path. command_exec: setblock a seeded loot chest, then data get it whole and its LootTableSeed (870/870 match the 26.3 oracle). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/commands.rs | 78 ++++++++++++++++++- .../horizon-client/src/game/commands/data.rs | 4 +- tools/command_exec_corpus.py | 6 ++ 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 38a5cddd3..8f934ad8a 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1885,11 +1885,12 @@ impl Game<'_> { } } } - let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else { + let Some((_, mut new)) = horizon_client::save::decode_block_entity(&tag) else { return false; }; + let rolled = self.take_loot_table(key, &tag, &mut new); let after = horizon_client::save::encode_block_entity(key, &new, &name); - if after == before { + if after == before && !rolled { return false; } self.world.block_entities.insert(key, new); @@ -1897,6 +1898,79 @@ impl Game<'_> { let _ = self.world.set(pos[0], pos[1], pos[2], state); true } + /// RandomizableContainer.tryLoadLootTable for a tag a command gives a + /// container (`setblock`, `data`): an empty container with a `LootTable` + /// is rolled now, as a loaded chunk's are (`save::roll_loaded_loot`), and + /// the roll is kept with its chunk, so that the container saves, and + /// `data get` shows, its table and seed until its items change. A tag + /// without one drops what the container had. True when it had a table. + pub(super) fn take_loot_table( + &mut self, + key: (i32, i32, i32), + tag: &horizon_world::nbt::Tag, + entity: &mut horizon_client::containers::BlockEntity, + ) -> bool { + use horizon_client::{containers::BlockEntity, save, structure_blocks}; + let table = save::text(tag.get("LootTable")); + let rolled = match (table, entity) { + (Some(table), BlockEntity::Chest(slots)) if slots.iter().all(Option::is_none) => { + let loot = structure_blocks::loot_data(&self.options.resources); + let at = Vec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); + let biome = self.biome_name_at(at).unwrap_or_default(); + Some(structure_blocks::roll_container( + slots, + loot.as_deref(), + table, + structure_blocks::loot_seed(tag), + key, + &biome, + )) + } + _ => None, + }; + let Some(chunk) = self.world.chunks.get_mut(&(key.0 >> 4, key.2 >> 4)) else { + return false; + }; + let held = |c: &horizon_client::chunk::Chunk| { + c.saved + .as_ref() + .is_some_and(|s| s.rolled_loot.iter().any(|r| r.pos == key)) + }; + if rolled.is_none() && !held(chunk) { + return false; + } + let chunk = std::sync::Arc::make_mut(chunk); + let mut extras = chunk + .saved + .take() + .map(std::sync::Arc::unwrap_or_clone) + .unwrap_or_default(); + extras.rolled_loot.retain(|r| r.pos != key); + let taken = rolled.is_some(); + extras.rolled_loot.extend(rolled); + chunk.saved = Some(std::sync::Arc::new(extras)); + taken + } + /// The loot table and seed a container still holding its roll saves + /// (`RolledLoot::restore`), in place of its items. + pub(super) fn restore_loot_table( + &self, + key: (i32, i32, i32), + tag: &mut horizon_world::nbt::Tag, + ) { + let horizon_world::nbt::Tag::Compound(map) = tag else { + return; + }; + let rolled = self + .world + .chunks + .get(&(key.0 >> 4, key.2 >> 4)) + .and_then(|c| c.saved.as_ref()) + .and_then(|s| s.rolled_loot.iter().find(|r| r.pos == key)); + if let Some(r) = rolled { + r.restore(map); + } + } fn cmd_fill(&mut self, ctx: &Context) -> R { let a = self.block_pos_arg(ctx, "from")?; let b = self.block_pos_arg(ctx, "to")?; diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 18035ddd7..ac16c5e7c 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -286,6 +286,7 @@ impl Game<'_> { if let Tag::Compound(c) = &mut tag { c.remove(&"keepPacked".into()); } + self.restore_loot_table(key, &mut tag); Ok(tag) } DataRef::Storage(id) => Ok(self.score.storage.get(id)), @@ -296,7 +297,8 @@ impl Game<'_> { DataRef::Entity(t) => self.apply_entity_nbt(*t, tag), DataRef::Block(p) => { let key = (p[0], p[1], p[2]); - if let Some((_, new)) = save::decode_block_entity(&tag) { + if let Some((_, mut new)) = save::decode_block_entity(&tag) { + self.take_loot_table(key, &tag, &mut new); self.world.block_entities.insert(key, new); let state = self.world.block(p[0], p[1], p[2]); // Redraw what shows the block entity (signs, banners). diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 0e3a7f92e..d8f925ef0 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -241,6 +241,12 @@ def world_blocks(): cmd('/clone 0 205 0 4 207 4 6 205 6 masked'), cmd('/execute if blocks 0 205 0 4 207 4 6 205 6 all'), cmd('/setblock 3 206 3 minecraft:air'), + # A container keeps its loot table and seed until its items change + # (RandomizableContainer.tryLoadLootTable / trySaveLootTable). + cmd('/setblock 7 206 7 minecraft:chest{LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:42L}'), + cmd('/data get block 7 206 7'), + cmd('/data get block 7 206 7 LootTableSeed'), + cmd('/setblock 7 206 7 minecraft:air'), # A hopper placed into power turns `enabled=false` and keeps its block entity. cmd('/setblock 5 205 5 minecraft:redstone_block'), cmd('/setblock 5 206 5 minecraft:hopper'), From 64f4e9b6ff2fd59b64dcf5811604bdcd524fdca7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:12:19 +0100 Subject: [PATCH 30/31] parity_hosts: playhorizon skips mob_ai, lan_integration, world_reopen (failed in its trial) Full trial (run 40341431094): 342/348 in 96.9 min; save_roundtrip, remote_fireball and server_player_sculk passed on a rerun with vscreen and fewer jobs; these three did not. Co-Authored-By: Claude Opus 5.5 --- tools/parity_hosts.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index f76a7f82c..b56106e4d 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -28,6 +28,11 @@ "python": "python3.13", "jobs": 6, "nice": 10, + "exclude": { + "mob_ai": "the vanilla oracle runs out of its 3 GB heap here (OutOfMemoryError in IO workers; passes on the desktop and the Mac) - 2026-10-26 trial", + "lan_integration": "two clients rendered on the CPU (lavapipe): different timing subtests fail on each run (elytra, consume-release, barter, critical-hits) - 2026-10-26 trial", + "world_reopen": "failed twice here (no Save and Quit button after reopening; the minecart-count flake), passes on the desktop - 2026-10-26 trial" + }, "note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)" } }, From 1825b3991cae222b6aac29951b5542abfb7c7f8a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:30:56 +0100 Subject: [PATCH 31/31] Campfires are no Container for droppers and hoppers Since campfires got their block entity (#2015), the container lookup took it for a zero-slot container: a dropper facing one kept its item instead of dropping it, as vanilla's HopperBlockEntity.getContainerAt finds no Container there. The dispense fixture also filled campfires through the generic slots, which a campfire doesn't have, so block_removal saw them empty. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dispense_fixture.rs | 5 +++++ crates/horizon-client/src/game/machines.rs | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 267f323c3..43f41d201 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -725,6 +725,11 @@ impl Game<'_> { match self.world.block_entities.get_mut(&p) { Some(BlockEntity::Jukebox(j)) => j.record = stack, Some(BlockEntity::Lectern(l)) => l.book = stack, + Some(BlockEntity::Campfire(c)) => { + if let Some(cell) = c.items.get_mut(slot) { + *cell = stack; + } + } Some(e) => { if let Some(cell) = e.slots_mut().get_mut(slot) { *cell = stack; diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 8742962e9..bb936744b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -159,8 +159,10 @@ impl Containers<'_> { }); } let entity = self.world.block_entities.get(&pos)?; - // A beehive keeps bees, not items: it is no `Container`. - if matches!(entity, BlockEntity::Beehive(_)) { + // A beehive keeps bees, not items, and a campfire cooks its own: neither + // is a `Container` (HopperBlockEntity.getContainerAt), so a dropper drops + // in front of them and a hopper leaves them alone. + if matches!(entity, BlockEntity::Beehive(_) | BlockEntity::Campfire(_)) { return None; } let kind = match (entity, name) {