Merge pull request #700 from ludovic111/fix/effects-every-player

🤖 Agent: merged by Ludovic's AI agent: perf-ticks-5 stack. Local on current main: clippy clean, horizon-client tests pass, parity 10/10 (dedicated_server lan tab_list chunk_stage locator_bar command_exec online_mode user_cache server_world_gen mob_ai); agent integration 88/88.
This commit is contained in:
Ludovic Marie
2026-10-17 22:11:26 +02:00
committed by GitHub
25 changed files with 1044 additions and 241 deletions
+34 -14
View File
@@ -71,6 +71,7 @@ mod lan_trading;
mod lan_waypoints;
mod leads;
mod level_particles;
mod levels;
mod lightning;
mod llamas;
mod loom;
@@ -975,8 +976,14 @@ struct Game<'a> {
world_root: PathBuf,
/// A player carried through a portal, re-placed once the destination loads.
travelling: Option<(PlayerMotion, Vec3)>,
/// A server's lone player on its way to another level.
server_trip: Option<server_travel::Trip>,
/// A server's players on their way to another level, each waiting for
/// the destination to load around them.
server_trips: Vec<server_travel::Trip>,
/// A server's levels other than the one in place (game/levels.rs).
levels: levels::Levels,
/// Which pass of a server tick runs (`tick_server`): the first one reads
/// the network, the last one ends the players' tick.
level_pass: levels::Pass,
/// Nether portals: the player's, items' and mobs' (game/nether_portal.rs).
portals: nether_portal::Portals,
/// The pending travel goes through an End portal (EndPortalBlock destinations).
@@ -1170,7 +1177,7 @@ struct Game<'a> {
/// The local player as a model (third person, the inventory).
player_model: Option<Mob>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Dim {
Overworld,
Nether,
@@ -3685,6 +3692,11 @@ impl Game<'_> {
) || self.book.is_some())
}
fn capture(&mut self, capture: bool) {
// A guest's action (`as_guest`) opens and closes screens on the
// guest's own client: the window's pointer stays the host's (#687).
if self.lan_acting.is_some() {
return;
}
// MouseHandler.grabMouse never captures an inactive window.
if capture && !self.focused {
return;
@@ -8460,18 +8472,10 @@ impl Game<'_> {
if self.remote.is_some() {
return Ok(());
}
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)));
self.save
.save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?;
if wait {
self.save.flush();
}
self.save_entities(wait)?;
self.save_level(wait)?;
self.save_parked_levels(wait)?;
self.save_maps();
self.save_random_sequences();
self.save_raids();
self.save_fight();
self.save_wandering_trader();
self.save_portal_arrivals();
@@ -8488,6 +8492,20 @@ impl Game<'_> {
self.message = Some(("Saved the game".into(), Instant::now()));
Ok(())
}
/// Save the level in place: its changed chunks, its entities and its raids.
fn save_level(&mut self, wait: bool) -> Result<()> {
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)));
self.save
.save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?;
if wait {
self.save.flush();
}
self.save_entities(wait)?;
self.save_raids();
Ok(())
}
fn render(&mut self) -> Result<bool> {
self.poll_shader_pack();
let Some(size) = self
@@ -10180,7 +10198,9 @@ impl<'a> Game<'a> {
dim: Dim::Overworld,
world_root: PathBuf::new(),
travelling: None,
server_trip: None,
server_trips: Vec::new(),
levels: Default::default(),
level_pass: Default::default(),
portals: Default::default(),
end_travel: false,
respawn_config: None,
+3
View File
@@ -469,6 +469,9 @@ impl Game<'_> {
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
"weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering },
"paused": self.pause,
// Mouse movement turns the camera (`apply_mouse_look`): the real
// pointer is grabbed, or an agent's `mouse-move` stands in for it.
"pointer_grabbed": self.captured || self.agent_pointer,
"player": player,
"selected": self.selected + 1,
"held": self.held().map(|s| self.stack_value(s)),
+4
View File
@@ -220,7 +220,11 @@ impl Game<'_> {
levels
}
/// `applyEffects`: the powers for players within `levels * 10 + 10` (any height above).
/// `BeaconBlockEntity.applyEffects`: every player in range.
fn beacon_effects(&mut self, p: [i32; 3], b: &Beacon) {
self.for_each_player(|g| g.beacon_effects_on_player(p, b));
}
fn beacon_effects_on_player(&mut self, p: [i32; 3], b: &Beacon) {
let Some(primary) = b.primary.as_deref().and_then(effect_id) else {
return;
};
@@ -362,3 +362,11 @@ pub(super) struct CreakingState {
/// Which block states are creaking hearts, by state id.
hearts: Vec<bool>,
}
impl CreakingState {
/// Exchange the chunks scanned for creaking hearts with another level's
/// (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
std::mem::swap(&mut self.scanned, &mut other.scanned);
}
}
+34 -7
View File
@@ -1358,25 +1358,52 @@ impl Game<'_> {
/// mining fatigue III for five minutes unless a stronger or longer one
/// is on, with the curse sound and the elder's apparition.
fn elder_curse(&mut self, at: [f64; 3]) {
let mut cursed = Vec::new();
self.for_each_player(|g| {
if g.elder_curse_player(at) {
cursed.push(g.lan_acting);
}
});
// A guest's client shows the apparition and plays the curse itself
// (ClientboundGameEventPacket.GUARDIAN_ELDER_EFFECT).
if let Some(host) = self.lan.as_ref() {
for conn in cursed.into_iter().flatten() {
host.hub.send_to(
conn,
&horizon_protocol::packets::play::Clientbound::GameEvent(
horizon_protocol::packets::play::GameEvent {
event: horizon_client::lan::hub::game_event::GUARDIAN_ELDER_EFFECT,
param: 1.0,
},
),
);
}
}
}
/// The curse on the player in place; whether it took.
fn elder_curse_player(&mut self, at: [f64; 3]) -> bool {
if self.creative || self.spectator() {
return;
return false;
}
let Some(p) = self.player.as_ref() else {
return;
return false;
};
let d = p.position.subtract(Vec3::new(at[0], at[1], at[2]));
if d.x * d.x + d.y * d.y + d.z * d.z >= 2500.0 || p.health.dead_or_dying() {
return;
return false;
}
let active = self.potions.effects.get("minecraft:mining_fatigue");
if active.is_some_and(|e| e.amplifier >= 2 && e.duration >= 1200) {
return;
return false;
}
let at = [p.position.x, p.position.y, p.position.z];
self.give_player_effect("minecraft:mining_fatigue", 6000, 2);
self.audio
.play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0);
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
if self.lan_acting.is_none() {
self.audio
.play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0);
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
}
true
}
/// Damage of a given type to the player from a point.
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
+12 -12
View File
@@ -642,18 +642,12 @@ impl Game<'_> {
);
self.save_game()?;
}
self.update_dedicated_streaming();
self.update_world();
if paused {
// MinecraftServer.tickServer: only the connections run.
self.tick_lan();
} else {
if !state.autosave {
// `save-off`: the periodic save inside the tick is skipped.
self.ticks = self.ticks.max(1);
}
self.tick()?;
if !paused && !state.autosave {
// `save-off`: the periodic save inside the tick is skipped.
self.ticks = self.ticks.max(1);
}
// MinecraftServer.tickServer: while paused only the connections run.
self.tick_server(paused)?;
if idle_timeout > 0 {
self.kick_idle(idle_timeout);
}
@@ -694,7 +688,13 @@ impl Game<'_> {
let center = self
.lan
.as_ref()
.and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk()))
.and_then(|h| {
h.hub
.guests
.iter()
.find(|g| h.hub.here(g))
.map(|g| g.chunk())
})
.or_else(|| {
self.spawn
.map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4))
@@ -23,7 +23,7 @@ impl Game<'_> {
.guests
.iter()
.filter(|g| {
g.placed
host.hub.here(g)
&& g.loaded
&& !g.dead
&& !g.creative()
+2 -4
View File
@@ -314,14 +314,12 @@ impl Game<'_> {
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.run_tasks();
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
// Only the connections run.
self.tick_lan();
self.tick_server(true)?;
} else {
let started = Instant::now();
self.tick()?;
self.tick_server(false)?;
self.debug_charts.log_tick(started, started.elapsed());
flags.smoothed_tick_ms.store(
self.debug_charts.smoothed_tick_ms.to_bits(),
+54 -6
View File
@@ -52,7 +52,7 @@ pub(super) struct LanHost {
/// Blocks broken this tick (their sound is a level event for the guests).
pub broken: Vec<[f64; 3]>,
/// Hurt and death state of the mobs guests see.
mob_state: HashMap<u32, (i32, bool)>,
mob_state: HashMap<super::Dim, HashMap<u32, (i32, bool)>>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
@@ -794,7 +794,19 @@ impl Game<'_> {
self.ui.rules.bool("player_movement_check"),
self.ui.rules.bool("elytra_movement_check"),
);
host.hub.tick(&mut ctx)
// A server with several levels runs a pass for each
// (`tick_server`): the network is read once, before the first.
let pass = self.level_pass;
let mut events = if pass.first {
host.hub.poll(&mut ctx)
} else {
Vec::new()
};
events.extend(host.hub.tick_level(&mut ctx));
if pass.last {
host.hub.end_tick();
}
events
};
if let Some(state) = &state
&& host.host_mode != state.game_mode
@@ -835,7 +847,15 @@ impl Game<'_> {
if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos)
&& !guest.spectator()
{
self.container_openers_changed(pos, false);
// In the level they were in.
let back = self.dim;
let theirs = super::Dim::from_id(&guest.dimension);
if self.enter_level(Some(&mut host), theirs).is_ok() {
self.container_openers_changed(pos, false);
}
if let Err(e) = self.enter_level(Some(&mut host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
}
self.lan_crafting_left(&mut host, &mut guest);
self.save_guest(&host, &guest);
@@ -892,6 +912,7 @@ impl Game<'_> {
let default_mode = host.hub.config.default_game_mode;
let force = host.hub.config.force_game_mode;
let root = self.world_root.clone();
let in_place = host.hub.config.dimension.clone();
let owner = host.owner.as_mut();
let Some(g) = host.hub.guest_mut(conn) else {
return;
@@ -914,8 +935,28 @@ impl Game<'_> {
g.previous_position = spawn;
g.health = 20.0;
g.food = 20;
g.dimension = super::Dim::Overworld.id().to_owned();
}
// A server places each player in their own level
// (`PlayerList.placeNewPlayer`); the in-frame game has one.
let back = self.dim;
let level = super::Dim::from_id(&g.dimension);
let elsewhere = self.options.dedicated.is_some() && level != back;
if !elsewhere {
g.dimension = in_place;
}
self.load_guest_records(host, conn);
let theirs;
let entities = if elsewhere {
if let Err(e) = self.enter_level(Some(host), level) {
log::error!("could not open {}: {e}", level.id());
return;
}
theirs = self.lan_entities(&mut host.hub);
&theirs[..]
} else {
entities
};
let mut ctx = TickCtx {
world: &mut self.world,
host: state,
@@ -930,6 +971,9 @@ impl Game<'_> {
collision: Some(self.collision),
};
host.hub.place_new_player(conn, &mut ctx);
if elsewhere && let Err(e) = self.enter_level(Some(host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
}
/// Level events the game queued, for the guests (`process_level_events`).
@@ -984,7 +1028,11 @@ impl Game<'_> {
let mut seen = HashMap::new();
for m in &self.mobs {
let dead = !m.alive();
let old = host.mob_state.get(&m.id).copied();
let old = host
.mob_state
.get(&self.dim)
.and_then(|s| s.get(&m.id))
.copied();
let at = [m.position.x, m.position.y, m.position.z];
if m.hurt_time > old.map_or(0, |o| o.0) && !dead {
host.hub.entity_event(m.id as i32, 2, at);
@@ -994,7 +1042,7 @@ impl Game<'_> {
}
seen.insert(m.id, (m.hurt_time, dead));
}
host.mob_state = seen;
host.mob_state.insert(self.dim, seen);
}
/// Keep the chunks around every guest loaded.
@@ -1003,7 +1051,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| g.placed)
.filter(|g| host.hub.here(g))
// The tracked square's corners and their lit neighbours lie
// within (view distance + 2) * √2 of the player's chunk.
.map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1))
+62 -10
View File
@@ -54,6 +54,8 @@ pub(super) struct GuestPlay {
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
pub(super) stats: super::stats::Stats,
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -140,13 +142,20 @@ impl Game<'_> {
total: g.xp_total,
},
);
let sneak = self.keys.contains(&KeyCode::ShiftLeft);
// The host's held keys stay theirs: the guest holds only sneak, and a
// screen the guest opens (`keys.clear()`) leaves the host walking.
let host_keys = std::mem::take(&mut self.keys);
if g.sneaking {
self.keys.insert(KeyCode::ShiftLeft);
} else {
self.keys.remove(&KeyCode::ShiftLeft);
}
// The window's screens are the host's: a sign, book, command block or
// mount menu the guest's action opens is not drawn over the host's
// world (#687). The guest's client opens its own.
let screen = std::mem::replace(&mut self.screen, Screen::Playing);
let host_sign = self.sign_edit.take();
let host_book = self.book.take();
let host_command_block = self.command_block_screen.take();
let host_mount_menu = std::mem::take(&mut self.mount_menu);
// The host's crafting grid stays theirs; a crafting table the guest
// opens shows as the 3x3 size.
let craft_size = std::mem::replace(&mut self.craft_size, 2);
@@ -205,11 +214,11 @@ impl Game<'_> {
play.swing = std::mem::replace(&mut self.swing, swing);
self.container = container;
self.screen = screen;
if sneak {
self.keys.insert(KeyCode::ShiftLeft);
} else {
self.keys.remove(&KeyCode::ShiftLeft);
}
self.sign_edit = host_sign;
self.book = host_book;
self.command_block_screen = host_command_block;
self.mount_menu = host_mount_menu;
self.keys = host_keys;
let g = &mut host.hub.guests[i];
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
@@ -282,6 +291,32 @@ impl Game<'_> {
Some(result)
}
/// `ServerLevel.players()` in turn: the host's own player, then each
/// guest in the level in place with their state swapped in (`as_guest`).
/// What reaches the players around a point (a beacon's powers, a splash
/// potion, a warden's darkness, an elder guardian's curse) lands on each
/// of them, not only on the host. A server has no player of its own.
/// Inside a guest's action (the hub taken) only that player is in place.
pub(super) fn for_each_player(&mut self, mut f: impl FnMut(&mut Self)) {
if self.player.is_some() {
f(self);
}
let Some(mut host) = self.lan.take() else {
return;
};
let conns: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
.map(|g| g.conn)
.collect();
for conn in conns {
self.as_guest(&mut host, conn, &mut f);
}
self.lan = Some(host);
}
/// The game mode fields without `set_mode`'s side effects on the host.
fn set_mode_raw(&mut self, id: i32) {
use horizon_client::command::args::GameMode;
@@ -937,7 +972,18 @@ impl Game<'_> {
if !host.hub.guests[i].dead {
return;
}
self.respawn_level(host);
// PlayerList.respawn: a server's player comes back in the Overworld,
// where the world spawn is (respawn anchors and beds aside).
let back = self.dim;
let away = self.options.dedicated.is_some()
&& host.hub.guests[i].dimension != super::Dim::Overworld.id();
if away {
self.server_trips.retain(|t| !t.is(conn));
if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) {
log::error!("could not open the Overworld: {e}");
return;
}
}
let g = &mut host.hub.guests[i];
g.dead = false;
g.health = 20.0;
@@ -974,6 +1020,9 @@ impl Game<'_> {
collision: Some(self.collision),
};
host.hub.respawn(i, spawn, &ctx);
if away && let Err(e) = self.enter_level(Some(host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
}
/// Per tick, for every guest: dig, use items, pick up drops, die.
@@ -984,7 +1033,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded)
.filter(|g| host.hub.here(g) && g.loaded)
.map(|g| g.conn)
.collect();
for conn in conns {
@@ -1376,6 +1425,9 @@ impl Game<'_> {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let (id, at) = (g.entity_id, g.position);
let play = host.play.get_mut(&conn).expect("play");
let swinging = play.swing.swinging() && play.swing.ticks == 0;
+7 -4
View File
@@ -92,7 +92,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead)
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
.map(|g| {
let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]);
(g.conn, g.uuid, moved)
@@ -138,7 +138,7 @@ impl Game<'_> {
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g)))
.collect()
}
@@ -209,9 +209,12 @@ pub(super) struct Present {
impl Game<'_> {
/// Every guest in the world (`ServerLevel.getPlayers` past the host).
pub(super) fn lan_present(&self) -> Vec<Present> {
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
let guests = self
.lan
.iter()
.flat_map(|h| h.hub.guests.iter().filter(|g| h.hub.here(g)));
guests
.filter(|g| g.placed && g.loaded)
.filter(|g| g.loaded)
.map(|g| {
let [x, y, z] = g.position;
Present {
+2 -2
View File
@@ -32,7 +32,7 @@ impl Game<'_> {
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?)))
.min_by(|a, b| a.1.total_cmp(&b.1))
}
@@ -64,7 +64,7 @@ impl Game<'_> {
host.hub
.guests
.iter()
.find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead)
.find(|g| g.entity_id == id && g.conn != conn && host.hub.here(g) && !g.dead)
.map(|g| Victim::Guest(g.conn))
}
@@ -372,7 +372,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.find(|g| g.conn == conn)
.find(|g| g.conn == conn && host.hub.here(g))
.map(|g| uuid_words(g.uuid))
else {
continue;
+350
View File
@@ -0,0 +1,350 @@
//! A server's levels, one per dimension (`MinecraftServer.levels`).
//!
//! 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
//! 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`).
//!
//! Shared by every level, as vanilla's derived levels share the
//! Overworld's level data: the game time, the day time and the weather, the
//! game rules, the scoreboard, the maps and the entities waiting to arrive
//! through a portal.
use super::{
Dim, ExperienceOrb, FallingBlock, Game, ItemEntity, Mob, boats, commands,
creaking::CreakingState, dragon, fireworks, lan::LanHost, lightning, machines, minecarts,
ominous_item_spawner, persist, raids::Raiding, sculk::SculkState, tnt, trident,
};
use horizon_client::{
Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections,
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World,
};
use horizon_world::level::{LevelEvent, Ticks};
use std::{collections::HashMap, sync::Arc};
/// Server ticks a level other than the Overworld stays loaded with no player
/// in it, before it is saved and closed (vanilla unloads a level's chunks
/// once no ticket holds them; the Overworld stays loaded).
const IDLE_TICKS: u32 = 300;
/// A level that is not in place: every per-level field of `Game`.
pub(super) struct Parked {
world: World,
streaming: Streaming,
save: Arc<SaveDir>,
block_ticks: Ticks,
tick_chunks: TickChunkMembership,
random_tick_sections: RandomTickSections,
level_events: Vec<LevelEvent>,
falling: Vec<FallingBlock>,
paintings: Vec<horizon_client::entities::Painting>,
item_frames: Vec<horizon_client::entities::ItemFrame>,
armor_stands: Vec<horizon_client::entities::ArmorStand>,
others: Vec<commands::OtherEntity>,
boats: Vec<boats::Boat>,
carts: Vec<minecarts::Minecart>,
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
bolts: Vec<lightning::Bolt>,
crystals: Vec<dragon::Crystal>,
dragon: Option<dragon::Dragon>,
dragon_fireballs: Vec<dragon::DragonFireball>,
breath_clouds: Vec<dragon::Breath>,
tridents: Vec<trident::ThrownTrident>,
rockets: Vec<fireworks::Rocket>,
ominous_spawners: Vec<ominous_item_spawner::OminousItemSpawner>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
mobs: Vec<Mob>,
projectiles: Vec<horizon_client::projectiles::Projectile>,
dropped: Vec<ItemEntity>,
orbs: Vec<ExperienceOrb>,
persist: persist::EntityMemory,
lectern_pulses: Vec<((i32, i32, i32), i32)>,
lid_openers: HashMap<(i32, i32, i32), i32>,
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
/// Only the per-level parts of these are used (`swap_level`).
anims: BlockEntityAnims,
raiding: Raiding,
sculk: SculkState,
creaking: CreakingState,
/// Server ticks since a player was last in the level.
idle: u32,
}
/// Which passes of the server tick the level in place runs: the first
/// reads the network (`Hub::poll`), the last ends the tick for every player
/// (`Hub::end_tick`). A tick with one level is both.
#[derive(Clone, Copy)]
pub(super) struct Pass {
pub first: bool,
pub last: bool,
}
impl Default for Pass {
fn default() -> Self {
Self {
first: true,
last: true,
}
}
}
/// The levels not in place, by dimension.
#[derive(Default)]
pub(super) struct Levels {
parked: HashMap<Dim, Parked>,
}
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> {
let (streaming, save) =
self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?;
let mut world = World::new(self.res.facts.air, self.level.seed);
world.fast_lava = dim == Dim::Nether;
Ok(Parked {
world,
streaming,
save,
block_ticks: Ticks::new(self.level.seed as i32),
tick_chunks: Default::default(),
random_tick_sections: Default::default(),
level_events: Vec::new(),
falling: Vec::new(),
paintings: Vec::new(),
item_frames: Vec::new(),
armor_stands: Vec::new(),
others: Vec::new(),
boats: Vec::new(),
carts: Vec::new(),
jukebox_sounds: HashMap::new(),
bolts: Vec::new(),
crystals: Vec::new(),
dragon: None,
dragon_fireballs: Vec::new(),
breath_clouds: Vec::new(),
tridents: Vec::new(),
rockets: Vec::new(),
ominous_spawners: Vec::new(),
tnts: Vec::new(),
hoppers: HashMap::new(),
mobs: Vec::new(),
projectiles: Vec::new(),
dropped: Vec::new(),
orbs: Vec::new(),
persist: Default::default(),
lectern_pulses: Vec::new(),
lid_openers: HashMap::new(),
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
anims: Default::default(),
raiding: Default::default(),
sculk: Default::default(),
creaking: Default::default(),
idle: 0,
})
}
/// Exchange the level in place with `p`.
fn swap_level(&mut self, p: &mut Parked) {
use std::mem::swap;
swap(&mut self.world, &mut p.world);
swap(&mut self.streaming, &mut p.streaming);
swap(&mut self.save, &mut p.save);
swap(&mut self.block_ticks, &mut p.block_ticks);
swap(&mut self.tick_chunks, &mut p.tick_chunks);
swap(&mut self.random_tick_sections, &mut p.random_tick_sections);
swap(&mut self.level_events, &mut p.level_events);
swap(&mut self.falling, &mut p.falling);
swap(&mut self.paintings, &mut p.paintings);
swap(&mut self.item_frames, &mut p.item_frames);
swap(&mut self.armor_stands, &mut p.armor_stands);
swap(&mut self.others, &mut p.others);
swap(&mut self.boats, &mut p.boats);
swap(&mut self.carts, &mut p.carts);
swap(&mut self.jukebox_sounds, &mut p.jukebox_sounds);
swap(&mut self.bolts, &mut p.bolts);
swap(&mut self.crystals, &mut p.crystals);
swap(&mut self.dragon, &mut p.dragon);
swap(&mut self.dragon_fireballs, &mut p.dragon_fireballs);
swap(&mut self.breath_clouds, &mut p.breath_clouds);
swap(&mut self.tridents, &mut p.tridents);
swap(&mut self.rockets, &mut p.rockets);
swap(&mut self.ominous_spawners, &mut p.ominous_spawners);
swap(&mut self.tnts, &mut p.tnts);
swap(&mut self.hoppers, &mut p.hoppers);
swap(&mut self.mobs, &mut p.mobs);
swap(&mut self.creatures.projectiles, &mut p.projectiles);
swap(&mut self.dropped, &mut p.dropped);
swap(&mut self.orbs, &mut p.orbs);
swap(&mut self.persist, &mut p.persist);
swap(&mut self.lectern_pulses, &mut p.lectern_pulses);
swap(&mut self.lid_openers, &mut p.lid_openers);
swap(&mut self.lan_events, &mut p.lan_events);
swap(&mut self.lan_block_events, &mut p.lan_block_events);
swap(&mut self.lan_entity_events, &mut p.lan_entity_events);
let (a, b) = (&mut self.be_anims, &mut p.anims);
swap(&mut a.chests, &mut b.chests);
swap(&mut a.books, &mut b.books);
swap(&mut a.shulkers, &mut b.shulkers);
swap(&mut a.bells, &mut b.bells);
swap(&mut a.conduits, &mut b.conduits);
swap(&mut a.skulls, &mut b.skulls);
swap(&mut a.pots, &mut b.pots);
swap(&mut a.gateways, &mut b.gateways);
swap(&mut a.gateway_servers, &mut b.gateway_servers);
self.raiding.swap_level(&mut p.raiding);
self.sculk.swap_level(&mut p.sculk);
self.creaking.swap_level(&mut p.creaking);
// What only the client draws starts over.
self.particles.clear();
self.pickups.clear();
}
/// Put `target`'s level in place, opening it first if it is not loaded.
/// The level that was in place is kept with the others; the shared
/// clock and weather go with the swap. `host` is the hub when the caller
/// holds it (`self.lan` is taken during the network tick).
pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> {
// The in-frame game keeps its one level (`enter_dimension`).
if self.options.dedicated.is_none() {
return Ok(());
}
if target != self.dim {
let (mut p, opened) = match self.levels.parked.remove(&target) {
Some(p) => (p, false),
None => (self.open_level(target)?, true),
};
p.world.game_time = self.world.game_time;
p.world.day_time = self.world.day_time;
p.world.weather = self.world.weather;
// The sculk tables' watched blocks are built once per game.
p.world.watched = std::mem::take(&mut self.world.watched);
self.swap_level(&mut p);
p.idle = 0;
let left = std::mem::replace(&mut self.dim, target);
self.levels.parked.insert(left, p);
if opened {
// The new streaming's radius and meshing options.
self.apply_settings();
}
}
let host = match host {
Some(h) => Some(h),
None => self.lan.as_mut(),
};
if let Some(h) = host {
h.hub.set_dimension(target.id());
}
Ok(())
}
/// 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
/// tick's shared parts (the clock, the weather, functions, the autosave);
/// the next ones only their level. While `paused`, only the connections
/// run.
pub(super) fn tick_server(&mut self, paused: bool) -> Result<()> {
let dims = self.levels_to_tick();
let n = dims.len();
let mut result = Ok(());
for (k, dim) in dims.into_iter().enumerate() {
if let Err(e) = self.enter_level(None, dim) {
result = Err(e);
break;
}
self.level_pass = Pass {
first: k == 0,
last: k + 1 == n,
};
self.update_dedicated_streaming();
self.update_world();
result = if paused {
self.tick_lan();
Ok(())
} else if k == 0 {
self.tick()
} else {
let running = self.clock.world_runs();
if running {
self.tick_weather_effects();
}
self.tick_world(running)
};
if result.is_err() {
break;
}
}
self.level_pass = Pass::default();
result?;
self.close_idle_levels()
}
/// The levels this server tick runs, in `MinecraftServer.levels` order
/// (the Overworld, the Nether, the End): every level with a player in
/// it, or the Overworld while nobody is online.
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
let guests = self
.lan
.as_ref()
.map_or(&[][..], |h| h.hub.guests.as_slice());
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
.into_iter()
.filter(|d| guests.iter().any(|g| g.dimension == d.id()))
.collect();
if dims.is_empty() {
dims.push(Dim::Overworld);
}
dims
}
/// Count the parked levels' empty ticks, and save and close the ones
/// (other than the Overworld) nobody has been in for a while.
pub(super) fn close_idle_levels(&mut self) -> Result<()> {
let occupied = self.levels_to_tick();
let mut closing = Vec::new();
for (dim, p) in &mut self.levels.parked {
if occupied.contains(dim) {
p.idle = 0;
continue;
}
p.idle += 1;
if *dim != Dim::Overworld && p.idle >= IDLE_TICKS {
closing.push(*dim);
}
}
if closing.is_empty() {
return Ok(());
}
let back = self.dim;
for dim in closing {
self.enter_level(None, dim)?;
self.save_level(true)?;
self.enter_level(None, back)?;
self.levels.parked.remove(&dim);
}
Ok(())
}
/// Save every parked level (`MinecraftServer.saveAllChunks`); the level
/// in place is the caller's to save.
pub(super) fn save_parked_levels(&mut self, wait: bool) -> Result<()> {
if self.levels.parked.is_empty() {
return Ok(());
}
let back = self.dim;
let dims: Vec<Dim> = self.levels.parked.keys().copied().collect();
for dim in dims {
self.enter_level(None, dim)?;
self.save_level(wait)?;
}
self.enter_level(None, back)
}
}
+38 -28
View File
@@ -467,6 +467,41 @@ impl Game<'_> {
self.splash(&stack, at);
}
}
/// A splash potion's effects on the player in place, by their distance.
fn splash_on_player(
&mut self,
effects: &'static [(&'static str, i32, i32)],
at: Vec3,
scale: f64,
) {
if let Some(p) = self.player.as_ref() {
let center = Vec3::new(
p.position.x,
p.position.y + f64::from(p.dimensions.height) / 2.0,
p.position.z,
);
let d2 =
(center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2);
if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) {
let intensity = 1.0 - d2.sqrt() / 4.0;
for (id, duration, amp) in effects {
let instant = brewing::effect(id).is_some_and(|e| e.instant);
if instant {
if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) {
self.apply_effect_action(a);
}
} else {
let d = (intensity * f64::from(*duration) * scale + 0.5) as i32;
if d > 20
&& let Some(e) = brewing::effect(id)
{
self.potions.effects.add(EffectInstance::new(e.id, d, *amp));
}
}
}
}
}
}
/// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash).
fn splash(&mut self, stack: &ItemStack, at: Vec3) {
if &*stack.item == "minecraft:experience_bottle" {
@@ -527,34 +562,9 @@ impl Game<'_> {
let Some(def) = stack.potion().and_then(brewing::potion) else {
return;
};
// The player.
if let Some(p) = self.player.as_ref() {
let center = Vec3::new(
p.position.x,
p.position.y + f64::from(p.dimensions.height) / 2.0,
p.position.z,
);
let d2 =
(center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2);
if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) {
let intensity = 1.0 - d2.sqrt() / 4.0;
for (id, duration, amp) in def.effects {
let instant = brewing::effect(id).is_some_and(|e| e.instant);
if instant {
if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) {
self.apply_effect_action(a);
}
} else {
let d = (intensity * f64::from(*duration) * scale + 0.5) as i32;
if d > 20
&& let Some(e) = brewing::effect(id)
{
self.potions.effects.add(EffectInstance::new(e.id, d, *amp));
}
}
}
}
}
// Every player in range (`ThrownSplashPotion.applySplash` over
// `LivingEntity`s, the players among them).
self.for_each_player(|g| g.splash_on_player(def.effects, at, scale));
// Mobs take the instant effects (undead invert healing and harming).
let undead = &self.res.stations.enchantments.entity_tags;
let mut hits = Vec::new();
+18 -7
View File
@@ -39,6 +39,17 @@ pub(super) struct Raiding {
homes: HashMap<i32, (i64, std::sync::Arc<Vec<[i32; 3]>>)>,
}
impl Raiding {
/// Exchange the level-held parts (`ServerLevel.getRaids`) with another
/// level's (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
std::mem::swap(&mut self.raids, &mut other.raids);
std::mem::swap(&mut self.loaded, &mut other.loaded);
std::mem::swap(&mut self.bar_hurts, &mut other.bar_hurts);
std::mem::swap(&mut self.homes, &mut other.homes);
}
}
/// `SectionPos` of a block position.
pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) {
(p[0] >> 4, p[1] >> 4, p[2] >> 4)
@@ -613,17 +624,17 @@ impl Game<'_> {
raider::state_mut(m).ticks_outside_raid = ticks;
}
}
Action::Victory { heroes, amplifier } => {
let me = self.level.player_uuid;
if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() {
// Raid.tick on a victory: each hero who is still alive.
Action::Victory { heroes, amplifier } => self.for_each_player(|g| {
if heroes.contains(&g.acting_uuid()) && !g.spectator() {
let mut effect =
EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier);
effect.visible = false;
self.potions.effects.add(effect);
self.stats.custom("raid_win", 1);
self.trigger_player("minecraft:hero_of_the_village");
g.potions.effects.add(effect);
g.stats.custom("raid_win", 1);
g.trigger_player("minecraft:hero_of_the_village");
}
}
}),
}
}
/// `Raid.playSound`: the horn, 13 blocks away from the player toward the
+15
View File
@@ -1463,6 +1463,21 @@ impl Game<'_> {
}
}
C::GameEvent(p) => match p.event {
// GUARDIAN_ELDER_EFFECT: the apparition, and the curse sound
// unless the elder guardian is silent.
10 => {
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
if p.param == 1.0
&& let Some(at) = self.player.as_ref().map(|m| m.position)
{
self.audio.play(
"minecraft:entity.elder_guardian.curse",
Some([at.x, at.y, at.z]),
1.0,
1.0,
);
}
}
1 => {
self.world.weather.raining = true;
self.world.weather.rain_level = (0.0, 0.0);
+12
View File
@@ -80,6 +80,15 @@ pub(super) struct SculkState {
ticks: u32,
pub tracker_loaded: bool,
}
impl SculkState {
/// Exchange the level-held parts (its sculk block entities and the
/// chunks scanned for them) with another level's (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
std::mem::swap(&mut self.index, &mut other.index);
std::mem::swap(&mut self.known, &mut other.known);
}
}
/// An insertion-ordered set of block positions (`Level.blockEntityTickers`
/// keeps the order block entities were added in).
#[derive(Default)]
@@ -1168,6 +1177,9 @@ impl Game<'_> {
/// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`.
pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) {
self.for_each_player(|g| g.darkness_on_player(at, radius));
}
fn darkness_on_player(&mut self, at: [f64; 3], radius: f64) {
if self.creative || self.spectator() {
return;
}
+141 -118
View File
@@ -1,59 +1,81 @@
//! A server's player between dimensions.
//! A server's players between dimensions.
//!
//! The server holds one level at a time, as the in-frame game does. While a
//! single player is online (single player on the server thread, or a world
//! with one player in it) that level follows the player through Nether and
//! End portals, and back to the Overworld when the player respawns. The swap
//! is the in-frame path's (`switch_level`, the portal plans, the arrival
//! search); the player hears it as `ServerPlayer.teleport` into another
//! level: a Respawn packet keeping all data, then a teleport to the exit once
//! the destination has loaded. With several players online the portals do
//! not take anyone yet: that needs the server to hold every level.
//! A server holds a level per dimension (game/levels.rs). A player who steps
//! into a Nether or End portal moves to the destination's level, which opens
//! if nobody was there: the swap is the in-frame path's portal plans and
//! arrival search, and the player hears it as `ServerPlayer.teleport` into
//! another level: a Respawn packet keeping all data, then a teleport to the
//! exit once the destination has loaded around them.
use super::nether_portal::PLAYER_DELAY;
use super::nether_portal::{PLAYER_DELAY, Plan};
use super::{Dim, Game, lan::LanHost};
use horizon_client::lan::hub::TickCtx;
use horizon_core::{geometry::Vec3, position::BlockPos};
/// A trip under way: the level has changed and its chunks are loading
/// around `target`.
/// A trip under way: the player is in the destination's level, whose
/// chunks are loading around `target`.
pub(super) struct Trip {
conn: u32,
dim: Dim,
target: Vec3,
/// Through an End portal (or out of the End by respawning).
/// Through an End portal.
end: bool,
/// The Nether portal plan, whose exit is found or built on arrival.
plan: Option<Plan>,
}
/// The lone player's box: Player's standing dimensions.
/// A player's box: Player's standing dimensions.
const WIDTH: f64 = 0.6;
const HEIGHT: f64 = 1.8;
impl Trip {
pub(super) fn is(&self, conn: u32) -> bool {
self.conn == conn
}
}
impl Game<'_> {
/// Whether `conn` is between two levels: the server leaves its body
/// alone until it arrives.
pub(super) fn on_server_trip(&self, conn: u32) -> bool {
self.server_trip.as_ref().is_some_and(|t| t.conn == conn)
self.server_trips.iter().any(|t| t.conn == conn)
}
/// Per server tick, after the guests' own: `Entity.handlePortal` for the
/// lone player (Nether portals count up their transition time, End
/// portals take it at once), or the arrival of the trip under way.
/// Per server tick in each level, after the guests' own: the arrivals of
/// the trips into this level, then `Entity.handlePortal` for each player
/// in it (Nether portals count up their transition time, End portals
/// take them at once).
pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) {
if self.options.dedicated.is_none() {
return;
}
if self.server_trip.is_some() {
self.arrive_server_trip(host);
return;
self.arrive_server_trips(host);
let conns: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| g.conn)
.collect();
for conn in conns {
if self.on_server_trip(conn) {
continue;
}
// `Entity.portalProcess` and `portalCooldown` are the player's own.
let mut portal = host.play.entry(conn).or_default().portal;
std::mem::swap(&mut self.portals.player, &mut portal);
self.handle_server_portal(host, conn);
std::mem::swap(&mut self.portals.player, &mut portal);
host.play.entry(conn).or_default().portal = portal;
}
let [g] = host.hub.guests.as_slice() else {
}
/// `Entity.handlePortal` for one player, whose portal state is in place.
fn handle_server_portal(&mut self, host: &mut LanHost, conn: u32) {
let Some(g) = host.hub.guest(conn) else {
return;
};
if !g.placed || !g.loaded || g.dead || g.spectator() {
return;
}
let (conn, at, invulnerable, sleeping) = (
g.conn,
let (at, invulnerable, sleeping) = (
Vec3::new(g.position[0], g.position[1], g.position[2]),
g.creative(),
g.sleeping,
@@ -70,7 +92,7 @@ impl Game<'_> {
} else {
Dim::End
};
self.start_server_trip(host, conn, target, true);
self.start_server_trip(host, conn, target, None);
}
// Entity.setAsInsidePortal while cooling down restarts the cooldown.
self.portals.player.cooldown = 10;
@@ -93,11 +115,10 @@ impl Game<'_> {
if !self.may_enter(plan.dim) {
return;
}
self.portals.travel = Some(plan);
self.start_server_trip(host, conn, plan.dim, false);
self.start_server_trip(host, conn, plan.dim, Some(plan));
}
/// A Nether portal block the lone player's box is in.
/// A Nether portal block a player's box is in.
fn nether_portal_inside(&self, at: Vec3) -> Option<BlockPos> {
let w = WIDTH / 2.0 - 1.0e-5;
let lo = [at.x - w, at.y + 1.0e-5, at.z - w];
@@ -114,9 +135,16 @@ impl Game<'_> {
None
}
/// The level swap, and the player told it is in the new level at the
/// approximate exit while it loads.
fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) {
/// The player moves to `target`'s level (opened if nobody was there)
/// and is told it is there, at the approximate exit, while it loads. The
/// level whose tick is running is put back in place afterwards.
fn start_server_trip(
&mut self,
host: &mut LanHost,
conn: u32,
target: Dim,
plan: Option<Plan>,
) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
@@ -124,105 +152,100 @@ impl Game<'_> {
let from = Vec3::new(g.position[0], g.position[1], g.position[2]);
let yaw = g.yaw;
let source = self.dim;
let end = plan.is_none();
// Coordinates scale by 8 between the Overworld and the Nether; an
// End portal has fixed destinations.
let scale = match (source, target) {
(Dim::Overworld, Dim::Nether) | (Dim::End, Dim::Nether) => 1.0 / 8.0,
(Dim::Nether, Dim::Overworld) => 8.0,
_ => 1.0,
};
self.end_portal_travel = end;
let switched = self.switch_level(target, from);
let scaled = self.end_destination(target).unwrap_or(Vec3::new(
from.x * scale,
from.y,
from.z * scale,
));
self.end_portal_travel = false;
let destination = match switched {
Ok(d) => d,
Err(e) => {
log::error!("could not open {}: {e}", target.id());
return;
}
if let Err(e) = self.enter_level(Some(host), target) {
log::error!("could not open {}: {e}", target.id());
return;
}
let destination = match plan {
Some(plan) => self.arrival_centre(&plan),
None => scaled,
};
let destination = match self.portals.travel {
Some(plan) if !end => self.arrival_centre(&plan),
_ => destination,
};
host.hub.set_dimension(target.id());
let at = [destination.x, destination.y, destination.z];
let ctx = self.server_ctx();
host.hub.change_level(i, at, yaw, &ctx);
self.as_guest(host, conn, |g| g.trigger_dimension(source, target));
self.server_trip = Some(Trip {
self.server_trips.push(Trip {
conn,
dim: target,
target: destination,
end,
plan,
});
if let Err(e) = self.enter_level(Some(host), source) {
log::error!("could not reopen {}: {e}", source.id());
}
}
/// Once the destination has loaded around the trip's target: the exit
/// (the Nether portal found or built, the End platform, the Overworld's
/// spawn column) and the teleport there.
fn arrive_server_trip(&mut self, host: &mut LanHost) {
let Some(trip) = self.server_trip.as_ref() else {
return;
};
let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else {
// They left on the way.
self.server_trip = None;
self.portals.travel = None;
return;
};
let (cx, cz) = (
(trip.target.x.floor() as i32) >> 4,
(trip.target.z.floor() as i32) >> 4,
);
if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
return;
}
let Some(trip) = self.server_trip.take() else {
return;
};
self.resolve_arrivals();
let (position, yaw) = if trip.end {
match self.end_arrival(trip.target) {
Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)),
Err(e) => {
log::error!("End arrival: {e}");
(trip.target, host.hub.guests[i].yaw)
}
/// The trips into the level in place whose destination has loaded
/// around their target: the exit (the Nether portal found or built, the
/// End platform, the Overworld's spawn column) and the teleport there.
fn arrive_server_trips(&mut self, host: &mut LanHost) {
let mut k = 0;
while k < self.server_trips.len() {
let trip = &self.server_trips[k];
let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else {
// They left on the way.
self.server_trips.remove(k);
continue;
};
let (cx, cz) = (
(trip.target.x.floor() as i32) >> 4,
(trip.target.z.floor() as i32) >> 4,
);
if trip.dim != self.dim
|| !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)))
{
k += 1;
continue;
}
} else {
let plan = self.portals.travel.take();
let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan));
match (plan, exit) {
(Some(plan), Some(exit)) => {
let (at, rotation) = self.arrival(&plan, exit);
(at, host.hub.guests[i].yaw + rotation)
let trip = self.server_trips.remove(k);
self.resolve_arrivals();
let yaw = host.hub.guests[i].yaw;
let (position, yaw) = if trip.end {
match self.end_arrival(trip.target) {
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
Err(e) => {
log::error!("End arrival: {e}");
(trip.target, yaw)
}
}
_ => (trip.target, host.hub.guests[i].yaw),
}
};
// Player.getDimensionChangingDelay.
self.portals.player.cooldown = 10;
let g = &mut host.hub.guests[i];
g.yaw = yaw;
// A new body at the exit: no fall distance or motion carried over.
g.motion = None;
host.hub
.teleport(i, Some([position.x, position.y, position.z]));
}
/// `PlayerList.respawn` away from the Overworld: the lone player's level
/// goes back to the Overworld first, where the world spawn is.
pub(super) fn respawn_level(&mut self, host: &mut LanHost) {
if self.options.dedicated.is_none() || self.dim == Dim::Overworld {
return;
} else {
let exit = trip
.plan
.as_ref()
.and_then(|plan| self.nether_exit_portal(plan));
match (trip.plan, exit) {
(Some(plan), Some(exit)) => {
let (at, rotation) = self.arrival(&plan, exit);
(at, yaw + rotation)
}
_ => (trip.target, yaw),
}
};
// Player.getDimensionChangingDelay.
host.play.entry(trip.conn).or_default().portal.cooldown = 10;
let g = &mut host.hub.guests[i];
g.yaw = yaw;
// A new body at the exit: no fall distance or motion carried over.
g.motion = None;
host.hub
.teleport(i, Some([position.x, position.y, position.z]));
}
if host.hub.guests.len() != 1 {
return;
}
self.server_trip = None;
self.portals.travel = None;
self.end_portal_travel = true;
let from = self.spawn.unwrap_or(Vec3::ZERO);
let switched = self.switch_level(Dim::Overworld, from);
self.end_portal_travel = false;
if let Err(e) = switched {
log::error!("could not open the Overworld: {e}");
return;
}
host.hub.set_dimension(Dim::Overworld.id());
}
/// The hub's view of the server for packets sent outside its own tick.
+2 -2
View File
@@ -25,7 +25,7 @@ impl Hub {
for g in self
.guests
.iter()
.filter(|g| g.placed && Some(g.conn) != except)
.filter(|g| self.here(g) && Some(g.conn) != except)
{
let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum();
if d <= range * range {
@@ -464,7 +464,7 @@ impl Hub {
let Some(menu) = self.guests[i]
.menu
.as_ref()
.filter(|_| self.guests[i].placed)
.filter(|_| self.here(&self.guests[i]))
else {
continue;
};
+4
View File
@@ -147,6 +147,9 @@ pub struct Guest {
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
/// The level the player is in (`ServerPlayer.level().dimension()`): the
/// hub's level passes only reach the players in theirs.
pub dimension: String,
/// The open block container, if any.
pub menu: Option<super::menu::Menu>,
pub next_window: i32,
@@ -248,6 +251,7 @@ impl Guest {
moves_from_ground: false,
dead: false,
placed: false,
dimension: "minecraft:overworld".into(),
menu: None,
next_window: 0,
drag: None,
+98 -16
View File
@@ -39,6 +39,7 @@ pub mod game_event {
pub const CHANGE_GAME_MODE: u8 = 3;
pub const RAIN_LEVEL: u8 = 7;
pub const THUNDER_LEVEL: u8 = 8;
pub const GUARDIAN_ELDER_EFFECT: u8 = 10;
pub const LEVEL_CHUNKS_LOAD_START: u8 = 13;
}
@@ -127,6 +128,9 @@ pub struct Hub {
last_rate: f32,
ticking: (f32, bool),
weather: (bool, f32, f32),
/// The clock and weather last sent in the levels not in place, by
/// dimension (`set_dimension` swaps them with the fields above).
level_sync: std::collections::HashMap<String, LevelSync>,
/// Operators and their permission levels (dedicated servers).
pub ops: std::collections::HashMap<u128, u8>,
chat_type: i32,
@@ -195,6 +199,24 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
/// What a level's players were last told of its clock and weather.
#[derive(Clone, Copy)]
struct LevelSync {
last_clock: i64,
last_rate: f32,
weather: (bool, f32, f32),
}
impl Default for LevelSync {
fn default() -> Self {
Self {
last_clock: i64::MIN,
last_rate: 0.0,
weather: (false, 0.0, 0.0),
}
}
}
impl Hub {
pub fn new(lan: Lan, sync: Arc<SyncData>, encoder: ChunkEncoder, config: HubConfig) -> Self {
let chat_type = sync
@@ -220,6 +242,7 @@ impl Hub {
ticking: (20.0, false),
ops: Default::default(),
weather: (false, 0.0, 0.0),
level_sync: Default::default(),
chat_type,
dimension_type,
clock_ids,
@@ -273,6 +296,18 @@ impl Hub {
g.sender.send(body.clone());
}
}
/// Whether a guest is placed in the level in place (`config.dimension`).
pub fn here(&self, g: &Guest) -> bool {
g.placed && g.dimension == self.config.dimension
}
/// `PlayerList.broadcastAll(packet, dimension)`: the players in the
/// level in place.
pub fn broadcast_level(&self, packet: &C) {
let body = packet.encode();
for g in self.guests.iter().filter(|g| self.here(g)) {
g.sender.send(body.clone());
}
}
pub fn broadcast_except(&self, conn: u32, packet: &C) {
let body = packet.encode();
for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) {
@@ -464,6 +499,7 @@ impl Hub {
guest.joined_tick = self.ticks;
guest.position = ctx.spawn;
guest.previous_position = ctx.spawn;
guest.dimension = self.config.dimension.clone();
self.guests.push(guest);
conn
}
@@ -875,7 +911,19 @@ impl Hub {
// ---- per tick ------------------------------------------------------
/// A whole tick with one level: the network, the level, then the
/// players' latencies.
pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
let mut events = self.poll(ctx);
events.extend(self.tick_level(ctx));
self.end_tick();
events
}
/// The network since the last tick, once per server tick before any
/// level ticks: joins (into the level in place), leaves, and each guest's
/// packets queued for its own level's pass.
pub fn poll(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
self.ticks += 1;
let mut events = Vec::new();
for event in self.lan.poll() {
@@ -911,13 +959,25 @@ impl Hub {
}
}
}
events
}
/// The level in place's part of the tick (`ServerLevel.tick`'s chunk
/// map and the connections of the players in it): their packets, then
/// the chunks, block changes, containers and entities they see.
pub fn tick_level(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
let mut events = Vec::new();
for i in 0..self.guests.len() {
if self.guests[i].placed {
if self.here(&self.guests[i]) {
self.process_inbox(i, ctx, &mut events);
}
}
if !self.guests.iter().any(|g| g.placed) {
if self.guests.is_empty() {
if !self.guests.iter().any(|g| self.here(g)) {
if !self
.guests
.iter()
.any(|g| g.dimension == self.config.dimension)
{
let _ = ctx.world.block_log.take();
}
return events;
@@ -927,7 +987,7 @@ impl Hub {
}
self.sync_world(ctx);
for i in 0..self.guests.len() {
if self.guests[i].placed {
if self.here(&self.guests[i]) {
self.update_chunks(i, ctx);
}
}
@@ -935,7 +995,7 @@ impl Hub {
// ServerGamePacketListenerImpl.tick: the actions handled since the last tick are
// acknowledged after the block changes they made were sent, so a client's predicted
// blocks settle on the server's states.
for g in &self.guests {
for g in self.guests.iter().filter(|g| self.here(g)) {
let sequence = g.ack_up_to.replace(-1);
if sequence >= 0 {
g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence }));
@@ -944,11 +1004,16 @@ impl Hub {
self.sync_containers(ctx.world);
self.track_entities(ctx);
for i in 0..self.guests.len() {
if self.guests[i].placed {
if self.here(&self.guests[i]) {
self.sync_player_state(i);
self.sync_effects(i);
}
}
events
}
/// After every level: `PlayerList.tick`.
pub fn end_tick(&mut self) {
let latencies: Vec<_> = self
.guests
.iter()
@@ -970,7 +1035,6 @@ impl Hub {
entries,
}));
}
events
}
fn remove_guest(&mut self, i: usize, reason: &str) -> Guest {
@@ -1001,7 +1065,7 @@ impl Hub {
// MinecraftServer.tickServer: the game time every 20 ticks
// (forceGameTimeSynchronization, no clocks).
if self.ticks.is_multiple_of(20) {
self.broadcast(&C::SetTime(play::SetTime {
self.broadcast_level(&C::SetTime(play::SetTime {
game_time: world.game_time,
clocks: Vec::new(),
}));
@@ -1017,7 +1081,7 @@ impl Hub {
.sync
.id("minecraft:world_clock", "minecraft:overworld")
.unwrap_or(0);
self.broadcast(&C::SetTime(play::SetTime {
self.broadcast_level(&C::SetTime(play::SetTime {
game_time: world.game_time,
clocks: vec![play::ClockState {
clock: overworld,
@@ -1036,7 +1100,7 @@ impl Hub {
let w = &world.weather;
let (raining, rain, thunder) = self.weather;
if w.raining != raining {
self.broadcast(&C::GameEvent(play::GameEvent {
self.broadcast_level(&C::GameEvent(play::GameEvent {
event: if w.raining {
game_event::START_RAINING
} else {
@@ -1046,13 +1110,13 @@ impl Hub {
}));
}
if (w.rain_level.1 - rain).abs() > f32::EPSILON {
self.broadcast(&C::GameEvent(play::GameEvent {
self.broadcast_level(&C::GameEvent(play::GameEvent {
event: game_event::RAIN_LEVEL,
param: w.rain_level.1,
}));
}
if (w.thunder_level.1 - thunder).abs() > f32::EPSILON {
self.broadcast(&C::GameEvent(play::GameEvent {
self.broadcast_level(&C::GameEvent(play::GameEvent {
event: game_event::THUNDER_LEVEL,
param: w.thunder_level.1,
}));
@@ -1183,7 +1247,7 @@ impl Hub {
for ((sx, sy, sz), positions) in sections {
let viewers: Vec<usize> = (0..self.guests.len())
.filter(|&i| {
self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz))
self.here(&self.guests[i]) && self.guests[i].sent_chunks.contains(&(sx, sz))
})
.collect();
if viewers.is_empty() {
@@ -1348,7 +1412,7 @@ impl Hub {
));
}
let placed: Vec<usize> = (0..self.guests.len())
.filter(|&i| self.guests[i].placed)
.filter(|&i| self.here(&self.guests[i]))
.collect();
let guest_states: Vec<_> = placed
.into_iter()
@@ -1388,7 +1452,7 @@ impl Hub {
.map(|e| super::entity::tracking_chunks(&e.kind))
.collect();
for gi in 0..self.guests.len() {
if !self.guests[gi].placed {
if !self.here(&self.guests[gi]) {
continue;
}
let view = self.guests[gi].view_distance;
@@ -1983,12 +2047,15 @@ impl Hub {
let mode = self.guests[i].game_mode;
let mut info = self.spawn_info(mode);
// Player.getLastDeathLocation, set where the player died.
// The level they died in: theirs until now.
info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos {
dimension: self.config.dimension.clone(),
dimension: self.guests[i].dimension.clone(),
pos,
});
self.close_container_for(i);
let g = &mut self.guests[i];
// PlayerList.respawn: into the level in place (the respawn level).
g.dimension = self.config.dimension.clone();
// ServerLevel.removePlayerImmediately: every entity paired with the dead player is
// removed (ServerEntity.removePairing, one packet each). Its chunks are dropped
// without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the
@@ -2057,6 +2124,20 @@ impl Hub {
/// The level the players are in: the server holds one at a time, and the
/// hub's packets name it.
pub fn set_dimension(&mut self, dimension: &str) {
if self.config.dimension == dimension {
return;
}
// What this level's players were told stays with it.
let leaving = LevelSync {
last_clock: self.last_clock,
last_rate: self.last_rate,
weather: self.weather,
};
let entering = self.level_sync.remove(dimension).unwrap_or_default();
self.level_sync
.insert(std::mem::take(&mut self.config.dimension), leaving);
(self.last_clock, self.last_rate, self.weather) =
(entering.last_clock, entering.last_rate, entering.weather);
self.config.dimension = dimension.to_owned();
self.dimension_type = self
.sync
@@ -2076,6 +2157,7 @@ impl Hub {
let info = self.spawn_info(mode);
self.close_container_for(i);
let g = &mut self.guests[i];
g.dimension = self.config.dimension.clone();
g.tracker.clear();
g.sent_chunks.clear();
g.chunk_queue.clear();
+5 -1
View File
@@ -71,6 +71,10 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = level.player_extra.clone();
guest.recipe_book = level.recipe_book.clone();
guest.dimension = match level.dimension.as_str() {
d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(),
_ => "minecraft:overworld".to_owned(),
};
if level.ender_items.len() == 27 {
guest.ender_items = level.ender_items.clone();
}
@@ -100,7 +104,6 @@ pub fn apply(guest: &mut Guest, level: &Level) {
pub fn save(guest: &Guest, world: &Path) {
let mut level = Level {
player_uuid: Some(uuid_ints(guest.uuid)),
dimension: "minecraft:overworld".into(),
..Level::default()
};
store(guest, &mut level);
@@ -114,6 +117,7 @@ pub fn save(guest: &Guest, world: &Path) {
/// Put a guest's state in `level`'s player fields.
pub fn store(guest: &Guest, level: &mut Level) {
level.position = Some(guest.position);
level.dimension = guest.dimension.clone();
level.rotation = [guest.yaw, guest.pitch];
level.health = guest.health;
level.food = guest.food;
+2 -2
View File
@@ -67,13 +67,13 @@ struct Remote { chat_input: Option<()> }
struct Game {
focused: bool, agent_pointer: bool, window: Option<Window>, mouse: Mouse,
captured: bool, title: Option<()>, screen: Screen, remote: Option<Remote>,
mining: bool,
mining: bool, lan_acting: Option<u32>,
}
impl Default for Game {
fn default() -> Self {
Self { focused: true, agent_pointer: false, window: Some(Window::default()),
mouse: Mouse::default(), captured: false, title: None,
screen: Screen::Playing, remote: None, mining: false }
screen: Screen::Playing, remote: None, mining: false, lan_acting: None }
}
}
impl Game {
+135 -6
View File
@@ -10,8 +10,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
- armour: each side draws the other player in that player's own armour;
- nametags: each side draws the other player's name above them;
- chest: a chest the guest opens opens on the guest's screen, its lid opens on both sides and
closes on both when the guest closes it;
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table;
closes on both when the guest closes it; the host keeps playing with its mouse look (#687);
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table, which
leaves the host's screen and mouse look alone;
- sign: a sign the guest places doesn't open a sign editor on the host;
- damage: a guest in survival takes fall damage;
- mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them;
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
@@ -19,7 +21,11 @@ address. The script then checks, from both sides, what a guest's game used to ge
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing;
- containers: the guest's ender chest holds the guest's items, not the host's, and a double chest
opens as 9x6 with the right half first;
- feedback: the guest's command feedback names the guest and shows the numbers.
- feedback: the guest's command feedback names the guest and shows the numbers;
- effects: a beacon's power reaches every player in range, the host and the guest;
- portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether
through a portal while the host stays, then the host goes to the End while the guest is in
the Nether, and both come back.
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
both sides go to --out (host-*.png, guest-*.png).
@@ -27,6 +33,7 @@ both sides go to --out (host-*.png, guest-*.png).
python3 tools/lan_e2e.py # build with the fast profile, run every check
python3 tools/lan_e2e.py --bin-dir target/fast # prebuilt binaries
python3 tools/lan_e2e.py --check chest --check tab
python3 tools/lan_e2e.py --server-thread --check portals # the host's world on its server thread
Needs the prepared resources in .local/horizon-client and, on Linux, vscreen (the desktop); on
macOS both games render offscreen. Games started here have no audio (HORIZON_NO_AUDIO=1).
@@ -48,7 +55,9 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials']
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'effects', 'portals']
class Game:
@@ -180,6 +189,19 @@ def check_nametags(host, guest, out):
return {'host': h, 'guest': g}
def grab(game):
"""Mouse look on, as a player's grabbed pointer: an agent's mouse-move stands in for it."""
game.raw('mouse-move', 1, 0)
game.raw('mouse-move', -1, 0)
def host_unaffected(host, what):
"""What a guest opens is the guest's: the host keeps its world on screen and its mouse look (#687)."""
state = host('state')
assert state.get('screen') == 'playing', f'{what} opened the {state.get("screen")} screen on the host'
assert state.get('pointer_grabbed'), f"{what} released the host's pointer"
def lid(game, pos):
return game.raw('block', *pos).get('lid', 0.0)
@@ -189,9 +211,11 @@ def check_chest(host, guest, out):
chest = (x, y, z + 2)
guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
guest.wait(10)
grab(host)
guest.raw('interact', *chest)
screen = guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
guest.wait(20)
host_unaffected(host, "the guest's chest")
opened = {'guest': lid(guest, chest), 'host': lid(host, chest)}
host.raw('look-at', chest[0] + 0.5, chest[1] + 0.5, chest[2] + 0.5)
host.wait(2)
@@ -231,8 +255,10 @@ def check_crafting(host, guest, out):
table = (x, y, z - 2)
guest('command', command=f'setblock {table[0]} {table[1]} {table[2]} minecraft:crafting_table')
guest.wait(10)
grab(host)
guest.raw('interact', *table)
guest.raw('wait-for', 'screen', 'inventory', '--timeout', 10)
host_unaffected(host, "the guest's crafting table")
size = guest('screen').get('craft_size')
assert size == 3, f'the crafting table opened a {size}x{size} grid'
# Two planks one above the other in the 3x3 grid: four sticks.
@@ -252,6 +278,104 @@ def check_crafting(host, guest, out):
return {'planks': planks, 'table': counts}
def check_sign(host, guest, out):
x, y, z = (int(v // 1) for v in pos_of(guest))
spot = (x + 2, y, z)
guest('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone')
guest('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air')
guest('command', command='give @s minecraft:oak_sign 1')
guest.wait(10)
grab(host)
guest.raw('place', *spot, '--item', 'minecraft:oak_sign')
guest.wait(20)
placed = host.raw('block', *spot).get('block')
host.shot(out, 'sign')
assert placed and 'sign' in placed, f'the guest placed {placed}'
host_unaffected(host, "the guest's sign")
return placed
def effect_ids(game):
return [e.get('id', '').removeprefix('minecraft:') for e in game('state')['player'].get('effects', [])]
def check_effects(host, guest, out):
x, y, z = (int(v // 1) for v in pos_of(host))
bx, by, bz = x - 3, y, z - 3
host('command', command=f'fill {bx - 1} {by - 1} {bz - 1} {bx + 1} {by - 1} {bz + 1} minecraft:iron_block')
host('command', command=f'setblock {bx} {by} {bz} minecraft:beacon{{primary_effect:"minecraft:speed"}}')
# BeaconBlockEntity.tick applies its powers every 80 ticks, once the beam has reached the sky.
seen = {}
for _ in range(15):
host.wait(20)
seen = {'host': effect_ids(host), 'guest': effect_ids(guest)}
if all('speed' in v for v in seen.values()):
break
host.shot(out, 'effects')
guest.shot(out, 'effects')
assert 'speed' in seen['host'] and 'speed' in seen['guest'], f'beacon effects: {seen}'
return seen
def wait_dimension(game, dimension, ticks):
"""Wait up to `ticks` for the game to be in `dimension` with its world loaded around it."""
for _ in range(ticks // 20):
state = game('state')
if state.get('dimension') == dimension and state.get('player'):
return state
game.wait(20)
return game('state')
def nether_portal(game, x, y, z):
"""A lit portal along x, two blocks wide and three tall, its inside starting at x y z."""
game('command', command=f'fill {x - 1} {y - 1} {z} {x + 2} {y + 3} {z} minecraft:obsidian')
game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]')
def check_portals(host, guest, out):
if not SERVER_THREAD:
return 'skipped (needs --server-thread)'
x, y, z = (int(v // 1) for v in pos_of(guest))
nether_portal(guest, x, y, z + 3)
guest.wait(5)
guest('command', command=f'tp @s {x + 0.5} {y} {z + 3.5}')
# players_nether_portal_default_delay: 80 ticks in survival.
there = wait_dimension(guest, 'minecraft:the_nether', 600)
guest.wait(40)
guest.shot(out, 'portals-nether')
host_dim = host('state').get('dimension')
assert there.get('dimension') == 'minecraft:the_nether', f'the guest is in {there.get("dimension")}'
assert host_dim == 'minecraft:overworld', f'the host went to {host_dim} with the guest'
arrived = [int(v // 1) for v in pos_of(guest)]
below = guest.raw('block', arrived[0], arrived[1] - 1, arrived[2])
assert below.get('loaded') and below.get('block') != 'minecraft:air', f'under the guest in the Nether: {below}'
# The host takes an End portal while the guest is in the Nether: three levels at once.
hx, hy, hz = (int(v // 1) for v in pos_of(host))
host('command', command=f'setblock {hx} {hy} {hz} minecraft:end_portal')
end = wait_dimension(host, 'minecraft:the_end', 600)
host.wait(40)
host.shot(out, 'portals-end')
guest_dim = guest('state').get('dimension')
assert end.get('dimension') == 'minecraft:the_end', f'the host is in {end.get("dimension")}'
assert guest_dim == 'minecraft:the_nether', f'the guest left the Nether for {guest_dim}'
# Both come back: the host through an exit portal, the guest out of its portal and in again.
ex, ey, ez = (int(v // 1) for v in pos_of(host))
host('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal')
host('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}')
guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] - 2.5}')
guest.wait(30)
guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] + 0.5}')
home = wait_dimension(host, 'minecraft:overworld', 600)
back = wait_dimension(guest, 'minecraft:overworld', 600)
guest.wait(40)
host.shot(out, 'portals-back')
guest.shot(out, 'portals-back')
assert home.get('dimension') == 'minecraft:overworld', f'the host stayed in {home.get("dimension")}'
assert back.get('dimension') == 'minecraft:overworld', f'the guest stayed in {back.get("dimension")}'
return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)}
def check_damage(host, guest, out):
guest('command', command='gamemode survival')
guest.wait(10)
@@ -623,14 +747,16 @@ def check_trials(host, guest, out):
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage,
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials,
'walls': check_walls}
'walls': check_walls, 'effects': check_effects, 'portals': check_portals}
def run(ctl, out, resources, checks):
host, guest = Game('host', ctl, resources), Game('guest', ctl, resources)
if SERVER_THREAD:
host.d.env['HORIZON_SERVER_THREAD'] = '1'
results = {}
try:
host('launch', wait=False, offscreen=sys.platform == 'darwin')
@@ -676,7 +802,10 @@ def main():
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
parser.add_argument('--check', action='append', choices=CHECKS, help='run only these checks (repeatable)')
parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game logs go here')
parser.add_argument('--server-thread', action='store_true', help="the host's world runs on its server thread")
args = parser.parse_args()
global SERVER_THREAD
SERVER_THREAD = args.server_thread
if args.bin_dir:
bins = Path(args.bin_dir).resolve()
else: