diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2760e0db5..0faca0ab4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7532,16 +7532,11 @@ impl Game<'_> { self.sleep_timer = 0; self.spawn = None; self.respawn_travel = None; - self.respawn_config = - self.level - .respawn_elsewhere - .as_ref() - .map(|(dim, pos, yaw, forced)| respawn_anchor::RespawnConfig { - dim: Dim::from_id(dim), - pos: *pos, - yaw: *yaw, - forced: *forced, - }); + self.respawn_config = self + .level + .respawn_elsewhere + .as_ref() + .map(respawn_anchor::RespawnConfig::from_saved); self.spawn_origin = None; self.spawn_spiral = Default::default(); self.player_spawn = None; @@ -9519,9 +9514,7 @@ impl Game<'_> { level.weather = self.world.weather; level.day_time = self.world.day_time; level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]); - level.respawn_elsewhere = self - .respawn_config - .map(|c| (c.dim.id().to_owned(), c.pos, c.yaw, c.forced)); + level.respawn_elsewhere = self.respawn_config.map(|c| c.saved()); level.rotation = [self.yaw, self.pitch]; level.xp_level = self.experience.level; level.xp_progress = self.experience.progress; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 570a64c09..c6877a839 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2285,12 +2285,23 @@ impl Game<'_> { }; let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0; let pitch = rot[1].clamp(-90.0, 90.0); - self.spawn = Some(Vec3::new( - f64::from(pos[0]) + 0.5, - f64::from(pos[1]), - f64::from(pos[2]) + 0.5, - )); - self.respawn_config = None; + // SetSpawnCommand: a forced point in the source's level. + if self.dim == Dim::Overworld { + self.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); + self.respawn_config = None; + } else { + self.spawn = None; + self.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos, + yaw, + forced: true, + }); + } let dim = Text::literal(self.dim.id()); let p = pos.map(|v| Text::literal(v.to_string())); let mut args = vec![ diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..67764c090 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -5,7 +5,7 @@ //! blocks, attacking and the commands all behave exactly as they do for the //! host, and every world change they cause reaches all players through the //! block log, the level events and the entity tracker. -use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost}; +use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost, respawn_anchor::RespawnConfig}; use horizon_client::{ command::vanilla, containers::BlockEntity, @@ -309,6 +309,7 @@ impl Game<'_> { g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])), ); let respawn = (self.respawn_config.take(), self.level.spawn); + self.respawn_config = g.respawn_elsewhere.as_ref().map(RespawnConfig::from_saved); let message = self.message.take(); // The guest's own ender inventory; one the host has open goes back // into the host's while the guest acts. @@ -470,7 +471,8 @@ impl Game<'_> { let bed = std::mem::replace(&mut self.sleeping, sleeping); let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer); let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]); - (self.respawn_config, self.level.spawn) = respawn; + let guest_respawn = std::mem::replace(&mut self.respawn_config, respawn.0); + self.level.spawn = respawn.1; // ServerPlayer.displayClientMessage(_, true): the guest's action bar. let guest_message = std::mem::replace(&mut self.message, message); let guest_vehicle = std::mem::replace(&mut self.riding, riding); @@ -507,6 +509,7 @@ impl Game<'_> { g.vehicle = guest_vehicle; let fell_asleep = bed.is_some() && g.bed.is_none(); (g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn); + g.respawn_elsewhere = guest_respawn.map(|c| c.saved()); g.sleeping = g.bed.is_some(); if let Some((text, _)) = guest_message { g.send(&C::SystemChat(play::SystemChat { @@ -1486,17 +1489,32 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } - // PlayerList.respawn: a server's player comes back in the Overworld, - // where the world spawn is (respawn anchors and beds aside). + // PlayerList.respawn: a server's player comes back in its respawn + // point's level: the Overworld, where the world spawn and beds are, + // or another one's anchor or forced point, which its block resolves + // once the level has loaded around it. + let server = self.options.dedicated.is_some(); + let elsewhere = host.hub.guests[i] + .respawn_elsewhere + .as_ref() + .filter(|_| server) + .map(RespawnConfig::from_saved); + let level = elsewhere.map_or(super::Dim::Overworld, |c| c.dim); + let spawn = elsewhere.map_or(spawn, |c| { + [ + f64::from(c.pos[0]) + 0.5, + f64::from(c.pos[1]), + f64::from(c.pos[2]) + 0.5, + ] + }); let back = self.dim; - let away = self.options.dedicated.is_some() - && host.hub.guests[i].dimension != super::Dim::Overworld.id(); - if away { + let away = server && host.hub.guests[i].dimension != level.id(); + if server { 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; - } + } + if away && let Err(e) = self.enter_level(Some(host), level) { + log::error!("could not open {}: {e}", level.id()); + return; } let g = &mut host.hub.guests[i]; g.dead = false; @@ -1535,6 +1553,9 @@ impl Game<'_> { collision: Some(self.collision), }; host.hub.respawn(i, spawn, &ctx); + if let Some(config) = elsewhere { + self.respawn_trip(conn, config); + } if away && let Err(e) = self.enter_level(Some(host), back) { log::error!("could not reopen {}: {e}", back.id()); } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 4604c076f..9b6ecc203 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -31,6 +31,24 @@ pub(super) struct RespawnConfig { pub forced: bool, } +/// A respawn point as a player's save keeps it (`respawn`): dimension, +/// block, yaw and whether it is forced. +pub(super) type SavedRespawn = (String, [i32; 3], f32, bool); + +impl RespawnConfig { + pub(super) fn from_saved((dim, pos, yaw, forced): &SavedRespawn) -> Self { + Self { + dim: Dim::from_id(dim), + pos: *pos, + yaw: *yaw, + forced: *forced, + } + } + pub(super) fn saved(&self) -> SavedRespawn { + (self.dim.id().to_owned(), self.pos, self.yaw, self.forced) + } +} + /// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block /// below, a block above, and straight above. const HORIZONTAL: [[i32; 3]; 8] = [ @@ -415,6 +433,16 @@ impl Game<'_> { let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5); (self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position) } + /// `Block.isPossibleToRespawnInThis`: neither solid nor liquid; banners, + /// signs and pressure plates override it to always. + fn possible_to_respawn_in(&self, state: BlockStateId) -> bool { + let f = self.res.facts().get(state); + let name = &*f.name; + name.ends_with("_banner") + || name.ends_with("_sign") + || name.ends_with("_pressure_plate") + || !(f.legacy_solid || matches!(name, "minecraft:water" | "minecraft:lava")) + } /// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the /// anchor, else any spot. pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option { @@ -428,8 +456,9 @@ impl Game<'_> { } None } - /// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the - /// loaded dimension: the position and yaw, using a charge. + /// `ServerPlayer.findRespawnAndUseSpawnBlock` for a config in the loaded + /// dimension: the position and yaw, using an anchor's charge. A forced + /// point (`spawnpoint`) that is no anchor holds if a player fits in it. pub(super) fn find_respawn_and_use( &mut self, c: RespawnConfig, @@ -440,7 +469,13 @@ impl Game<'_> { && (c.forced || self.anchor_charges(state) > 0) && self.anchor_works()) { - return Ok(None); + let [x, y, z] = c.pos; + let free = c.forced + && !self.is_anchor(state) + && self.possible_to_respawn_in(state) + && self.possible_to_respawn_in(self.world.block(x, y + 1, z)); + let at = Vec3::new(f64::from(x) + 0.5, f64::from(y) + 0.1, f64::from(z) + 0.5); + return Ok(free.then_some((at, c.yaw))); } let stand = self.anchor_stand_up(c.pos); if !c.forced diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index b7462baa8..1b1ec3a6d 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -9,8 +9,9 @@ use super::end::GatewayJob; use super::nether_portal::{PLAYER_DELAY, Plan}; +use super::respawn_anchor::RespawnConfig; use super::{Dim, Game, lan::LanHost}; -use horizon_client::lan::hub::TickCtx; +use horizon_client::{lan::hub::TickCtx, text::Text}; use horizon_core::{geometry::Vec3, position::BlockPos}; /// A trip under way: the player is in the destination's level, whose @@ -26,6 +27,9 @@ pub(super) struct Trip { /// Through an End gateway, within the level: its exit, found or built /// on arrival. gateway: Option, + /// A respawn at this point outside the Overworld, resolved through its + /// block on arrival. + respawn: Option, /// Sent by a command: the player is already where it goes. placed: bool, } @@ -215,6 +219,7 @@ impl Game<'_> { end, plan, gateway: None, + respawn: None, placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { @@ -222,6 +227,64 @@ impl Game<'_> { } } + /// A respawned player waits at its point outside the Overworld for the + /// level to load around it. + pub(super) fn respawn_trip(&mut self, conn: u32, config: RespawnConfig) { + let [x, y, z] = config.pos; + self.server_trips.push(Trip { + conn, + dim: config.dim, + target: Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5), + end: false, + plan: None, + gateway: None, + respawn: Some(config), + placed: false, + }); + } + + /// `findRespawnAndUseSpawnBlock` for the player in place, at its point + /// in the level in place: where it stands up, facing the anchor, with + /// the deplete sound; else the point is forgotten + /// (`block.minecraft.spawn.not_valid`). + fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> { + match self.find_respawn_and_use(config, true) { + Ok(Some((at, yaw))) => { + if !config.forced { + let [x, y, z] = config.pos.map(f64::from); + self.audio.play( + "minecraft:block.respawn_anchor.deplete", + Some([x, y, z]), + 1.0, + 1.0, + ); + } + Some((at, yaw)) + } + Ok(None) | Err(_) => { + self.respawn_config = None; + self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[])); + None + } + } + } + + /// TeleportTransition.missingRespawnBlock: the world spawn, in the + /// Overworld. + fn respawn_at_world_spawn(&mut self, host: &mut LanHost, conn: u32) { + let at = self.level.world_spawn.map_or( + self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]), + |[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5], + ); + self.level_teleports.push(LevelTeleport { + conn, + dim: Dim::Overworld, + at, + rotation: None, + }); + self.run_level_teleports(host); + } + /// `TheEndGatewayBlockEntity.getPortalPosition` and the teleport within /// the End (keeping the player's motion and look): straight to an exact /// exit, else once the destination has loaded around the player, who @@ -244,6 +307,7 @@ impl Game<'_> { end: false, plan: None, gateway: Some(job), + respawn: None, placed: false, }); } @@ -276,7 +340,15 @@ impl Game<'_> { } self.resolve_arrivals(); let yaw = host.hub.guests[i].yaw; - let (position, yaw) = if let Some(job) = trip.gateway { + let (position, yaw) = if let Some(config) = trip.respawn { + match self.as_guest(host, trip.conn, |g| g.resolve_server_respawn(config)) { + Some(Some(found)) => found, + _ => { + self.respawn_at_world_spawn(host, trip.conn); + continue; + } + } + } else if let Some(job) = trip.gateway { match self.resolve_gateway(job, trip.target) { Ok(at) => (at, yaw), Err(e) => { @@ -346,6 +418,7 @@ impl Game<'_> { end: false, plan: None, gateway: None, + respawn: None, placed: true, }); if let Err(e) = self.enter_level(Some(host), source) { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 1916344bb..948de7e20 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -93,6 +93,10 @@ pub struct Guest { /// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`), /// None for the world spawn. pub spawn: Option<[f64; 3]>, + /// A respawn point outside the Overworld (a respawn anchor, or one + /// `spawnpoint` set there): its dimension, block, yaw and whether it is + /// forced, as the player's save keeps it (`respawn`). + pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>, /// Pending ClientboundPlayerPositionPacket id; movement is ignored until /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, @@ -252,6 +256,7 @@ impl Guest { sleep_timer: 0, sent_bed: None, spawn: None, + respawn_elsewhere: None, awaiting_teleport: None, teleport_counter: 0, teleport_tick: 0, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..24a4a9d65 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -72,6 +72,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.flying = level.flying; guest.selected = (level.selected_slot.max(0) as usize).min(8); guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); + guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { @@ -135,6 +136,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.flying = guest.flying; level.selected_slot = guest.selected as i32; level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); + level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); level.recipe_book = guest.recipe_book.clone(); diff --git a/docs/server-levels.md b/docs/server-levels.md index eee730f89..a44f290c4 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -18,7 +18,7 @@ the other dimensions' levels as `Parked` values and swaps one into place (`enter | `MinecraftServer.tickChildren`, every level | `tick_server`: each level with a player in it, in Overworld, Nether, End order. The first pass reads the network and runs the shared parts (clock, weather, functions, autosave). | | `ServerLevel.players` | `Hub::here`: the guests whose `dimension` is the level in place | | `ServerPlayer.teleport` into another level | `server_travel.rs`: a Respawn packet, then the teleport once the destination has loaded (portals and `execute in … tp`). An End gateway teleports within the End. | -| `PlayerList.respawn` | `guest_respawn`: back into the Overworld's level | +| `PlayerList.respawn` | `guest_respawn`: into the respawn point's level, the Overworld unless the player has an anchor or a `spawnpoint` elsewhere (`Guest::respawn_elsewhere`), resolved through its block once that level has loaded | | `ServerLevel.noPlayersEmptyTime`, chunk unloading | `close_idle_levels`: a level other than the Overworld with nobody in it for 300 ticks is saved and closed | | `CommandSourceStack.getLevel` | `with_source` puts the source's level in place for a command (`execute in`, `execute at` a player in another level) | | the levels' shared `LevelData` | not swapped: game time, day time, weather, game rules, scoreboard, maps, entity ids (`next_entity`, unique across levels) | @@ -76,7 +76,8 @@ the Nether, or whose host saves and quits, joins again in the Nether where it wa - Mobs and armour stands fall in two levels at once, and every entity id is unique across the levels. - The guest leaves in the Nether and joins again there. - - The guest dies in the Nether and respawns in the Overworld. + - The guest dies in the Nether and respawns in the Overworld. With a `spawnpoint` and then a + respawn anchor set in the Nether, it respawns there, and the anchor loses a charge. - The host takes a Nether portal alone. - The guest takes an End portal, an End gateway and then the exit portal alone. - The host saves, quits and opens the world again with the guest in the Nether, and the guest diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 85778d91d..79250678e 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -70,7 +70,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - levels: (--server-thread) the host and the guest each in a level of their own: `execute in` teleports into another level, and `execute in` and `at` change and test blocks there; mobs fall in two levels at once, with ids unique across them; the guest rejoins in the - Nether, dies there and respawns in the Overworld; the host takes a Nether portal alone; + Nether, dies there and respawns in the Overworld, then in the Nether at a `spawnpoint` + and at a respawn anchor set there; the host takes a Nether portal alone; the guest takes an End portal, an End gateway and the exit portal alone; and the host saves, quits and reopens with the guest in the Nether. - commands: the guest's chat completes commands and their arguments over the server's command @@ -696,6 +697,48 @@ def level_death(host, guest, out): return {'respawned': back['player']['position']} +def level_respawn_points(host, guest, out): + """Respawn points outside the Overworld (ServerPlayer.findRespawnAndUseSpawnBlock): a point + `spawnpoint` sets in the Nether (forced), then a charged respawn anchor the guest uses there, + each bring the guest back in the Nether; the anchor loses a charge.""" + home = pos_of(guest) + x, z = (int(v // 1) for v in home[::2]) + into_level(guest, NETHER, x, 100, z) + results = {} + try: + guest('command', command=f'spawnpoint @s {x} 100 {z}') + results['spawnpoint'] = die_and_respawn(guest) + guest('command', command=f'setblock {x + 2} 100 {z} minecraft:respawn_anchor[charges=2]') + guest.wait(10) + guest.raw('interact', x + 2, 100, z) + guest.wait(10) + results['anchor'] = die_and_respawn(guest) + results['charges'] = guest.raw('block', x + 2, 100, z).get('state') + finally: + sx, sy, sz = (int(v // 1) for v in pos_of(host)) + guest('command', command=f'execute in {OVERWORLD} run spawnpoint @s {sx} {sy} {sz}') + guest('command', command=f'execute in {NETHER} run setblock {x + 2} 100 {z} minecraft:air') + guest('command', command=f'execute in {OVERWORLD} run tp @s {home[0]:.2f} {home[1]:.2f} {home[2]:.2f}') + wait_dimension(guest, OVERWORLD, 400) + point, anchor = results['spawnpoint'], results['anchor'] + assert point[0] == NETHER and abs(point[1][0] - x - 0.5) < 0.6 and abs(point[1][2] - z - 0.5) < 0.6, \ + f'the spawnpoint brought the guest to {point}' + assert anchor[0] == NETHER and abs(anchor[1][0] - x - 2.5) < 2 and abs(anchor[1][2] - z - 0.5) < 2, \ + f'the anchor brought the guest to {anchor}' + assert 'charges=1' in (results['charges'] or ''), f'the anchor after the respawn: {results["charges"]}' + return results + + +def die_and_respawn(guest): + """Kill the guest and respawn it: the dimension and position it comes back at, once settled.""" + guest('command', command='kill @s') + guest.wait(20) + guest.raw('respawn') + guest.wait(80) + state = guest('state') + return state.get('dimension'), state['player']['position'] + + def level_host_nether(host, guest, out): """The host goes through a Nether portal while the guest stays in the Overworld.""" hx, hy, hz = (int(v // 1) for v in pos_of(host)) @@ -788,7 +831,8 @@ def level_reload(host, guest, out): LEVEL_STEPS = [('execute', level_execute), ('ticking', level_ticking), ('rejoin', level_rejoin), - ('death', level_death), ('host_nether', level_host_nether), + ('death', level_death), ('respawn_points', level_respawn_points), + ('host_nether', level_host_nether), ('guest_end', level_guest_end), ('reload', level_reload)]