From 951b88a3c299c1221cbd317481e6bbf1c9d1b8f1 Mon Sep 17 00:00:00 2001 From: Carlos Nunez Date: Mon, 26 Oct 2026 16:36:53 -0400 Subject: [PATCH 1/2] Read an End gateway's exit from its block entity Horizon had no End gateway block entity: game/end.rs kept each gateway's exit in its own side file and gateway_job only looked there, so a gateway set with /setblock end_gateway{exit_portal:[I;..],ExactTeleport:1b} (or the exit worldgen writes) was ignored, and /data get block said the block was not a block entity. TheEndGatewayBlockEntity stores Age, exit_portal and ExactTeleport. BlockEntity::EndGateway now holds them with vanilla's NBT and the spawnable-bounds check. gateway_job reads the block entity's exit first and keeps the side file and the 512-block End-spawn rule as fallbacks, so older saves and gateways without data behave as before. The exits Horizon creates are stored in the block entity as well, a new exit keeps the gateway's own ExactTeleport (setExitPosition), and a command that only changes a block entity's NBT now marks its chunk modified so the change is saved. Fixes #1517. Implementation by Codex (GPT-6.1 Sol), reviewed and extended by Claude. Co-Authored-By: Codex (GPT-6.1 Sol) Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/block_entity_nbt.rs | 15 +- crates/horizon-client/src/containers.rs | 16 ++ crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/commands.rs | 3 +- crates/horizon-client/src/game/end.rs | 177 +++++++++++++++--- crates/horizon-client/src/save.rs | 97 ++++++++++ crates/horizon-client/src/structure_blocks.rs | 20 ++ 7 files changed, 302 insertions(+), 28 deletions(-) diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client/src/block_entity_nbt.rs index a4c02ba3b..67cd3591f 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client/src/block_entity_nbt.rs @@ -61,6 +61,16 @@ fn f32_tag(v: f32) -> Tag { Tag::Float(v.to_bits()) } +/// `TheEndGatewayBlockEntity.loadAdditional`: BlockPos.CODEC and Level.isInSpawnableBounds. +pub(crate) fn gateway_exit(tag: &Tag) -> Option<[i32; 3]> { + let Tag::IntArray(v) = tag else { return None }; + let p: [i32; 3] = v.as_slice().try_into().ok()?; + ((-30_000_000..30_000_000).contains(&p[0]) + && (-20_000_000..20_000_000).contains(&p[1]) + && (-30_000_000..30_000_000).contains(&p[2])) + .then_some(p) +} + /// What a block entity reads and writes, in `saveAdditional` order. struct Fields<'a> { input: &'a Tag, @@ -424,10 +434,7 @@ pub fn canonical(tag: &Tag) -> Option { } "minecraft:end_gateway" => { f.long("Age", 0); - f.keep("exit_portal", |t| { - is_pos(t) - && matches!(t, Tag::IntArray(v) if v[1].abs() <= 30_000_000 && v[0].abs() <= 30_000_000 && v[2].abs() <= 30_000_000) - }); + f.keep("exit_portal", |t| gateway_exit(t).is_some()); if flag(tag.get("ExactTeleport")) == Some(true) { f.put("ExactTeleport", boolean(true)); } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 8ca9af0ad..81c453f32 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -98,10 +98,19 @@ pub enum BlockEntity { Campfire(Box), /// `SkullBlockEntity` of every skull and head block. Skull(Skull), + /// `TheEndGatewayBlockEntity`: its age and configured destination. + EndGateway(EndGateway), /// `DaylightDetectorBlockEntity`: no data, only the ticker /// (`DaylightDetectorBlock.tickEntity`). DaylightDetector, } +/// `TheEndGatewayBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EndGateway { + pub age: i64, + pub exit_portal: Option<[i32; 3]>, + pub exact_teleport: bool, +} /// `CampfireBlockEntity`: four cooking slots, each with its /// `cookingProgress` and `cookingTime` (the recipe's). #[derive(Clone, Debug, Default, PartialEq)] @@ -366,6 +375,9 @@ impl BlockEntity { if is_skull(name) { return Some(Self::Skull(Skull::default())); } + if name == "minecraft:end_gateway" { + return Some(Self::EndGateway(EndGateway::default())); + } if name == "minecraft:daylight_detector" { return Some(Self::DaylightDetector); } @@ -418,6 +430,7 @@ impl BlockEntity { Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", Self::Skull(_) => "minecraft:skull", + Self::EndGateway(_) => "minecraft:end_gateway", Self::DaylightDetector => "minecraft:daylight_detector", Self::Campfire(_) => "minecraft:campfire", } @@ -436,6 +449,7 @@ impl BlockEntity { | Self::Vault(_) | Self::Beehive(_) | Self::CommandBlock(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), @@ -456,6 +470,7 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, @@ -480,6 +495,7 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 20f6e01bc..145e55554 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5455,6 +5455,7 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector | BlockEntity::Campfire(_), @@ -5727,6 +5728,7 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector | BlockEntity::Campfire(_), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 22041c3b2..b9a462d87 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1896,8 +1896,7 @@ impl Game<'_> { return false; } self.world.block_entities.insert(key, new); - let state = self.world.block(pos[0], pos[1], pos[2]); - let _ = self.world.set(pos[0], pos[1], pos[2], state); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); true } /// RandomizableContainer.tryLoadLootTable for a tag a command gives a diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 32d5113b0..e8b9a96e3 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -5,6 +5,7 @@ use super::{Dim, Game}; use horizon_client::{ Result, + containers::BlockEntity, environment::Environment, items::ItemStack, mesher::Vertex, @@ -27,14 +28,53 @@ const GATEWAY_Y: i32 = 75; const GATEWAY_FILE: &str = "horizon-end-gateways.json"; /// A gateway teleport waiting for its destination chunks. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum GatewayJob { /// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway. - Find { gateway: [i32; 3] }, + /// `exact` is the gateway's own `ExactTeleport`, read while its chunk is loaded. + Find { gateway: [i32; 3], exact: bool }, /// A known exit (exact, or findExitPosition around it). Known { exit: [i32; 3], exact: bool }, } +impl GatewayJob { + /// TheEndGatewayBlockEntity.getPortalPosition, with legacy save fallbacks. + fn for_gateway( + gateway: [i32; 3], + entity: Option<&BlockEntity>, + legacy: Option<([i32; 3], bool)>, + ) -> Self { + let configured = match entity { + Some(BlockEntity::EndGateway(g)) => g.exit_portal.map(|exit| (exit, g.exact_teleport)), + _ => None, + }; + match configured.or(legacy) { + Some((exit, exact)) => Self::Known { exit, exact }, + // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. + None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => Self::Known { + exit: END_SPAWN, + exact: true, + }, + None => Self::Find { + gateway, + exact: exact_teleport(entity), + }, + } + } +} + +/// `TheEndGatewayBlockEntity.exactTeleport` of the block entity at a gateway +/// (false without one). +fn exact_teleport(entity: Option<&BlockEntity>) -> bool { + matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport) +} + +/// The end of `getPortalPosition`: the exit itself when the teleport is exact, +/// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`). +fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] { + if exact { exit } else { find(exit) } +} + #[derive(Default)] pub(super) struct EndState { /// Gateway position -> (exit, exact teleport); loaded lazily from the save. @@ -754,6 +794,11 @@ impl Game<'_> { } } } + self.world + .block_entities + .get_or_insert_with((origin[0], origin[1], origin[2]), || { + BlockEntity::EndGateway(Default::default()) + }); Ok(()) } @@ -776,6 +821,21 @@ impl Game<'_> { } fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { + // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + // The gateway's chunk can be unloaded by now (travel waits for the destination): the + // side map below still records the exit. + if self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + g.exit_portal = Some(exit); + g.exact_teleport = exact; + self.world.modified.insert(chunk); + } self.gateway_exits().insert(gateway, (exit, exact)); let list: Vec<_> = self .gateway_exits() @@ -808,24 +868,20 @@ impl Game<'_> { /// is resolved ([`Game::resolve_gateway`]). pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { let known = self.gateway_exits().get(&gateway).copied(); - let job = match known { - Some((exit, exact)) => GatewayJob::Known { exit, exact }, - // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. - None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => { - GatewayJob::Known { - exit: END_SPAWN, - exact: true, - } - } - None => GatewayJob::Find { gateway }, - }; + let job = GatewayJob::for_gateway( + gateway, + self.world + .block_entities + .get(&(gateway[0], gateway[1], gateway[2])), + known, + ); let destination = match job { GatewayJob::Known { exit, .. } => Vec3::new( f64::from(exit[0]) + 0.5, f64::from(exit[1]), f64::from(exit[2]) + 0.5, ), - GatewayJob::Find { gateway } => { + GatewayJob::Find { gateway, .. } => { let d = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero() * 1024.0; @@ -882,12 +938,10 @@ impl Game<'_> { [p[0], p[1] + 1, p[2]] }; match job { - GatewayJob::Known { exit, exact } => Ok(bottom_center(if exact { - exit - } else { - find_exit(self, exit) - })), - GatewayJob::Find { gateway } => { + GatewayJob::Known { exit, exact } => Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))), + GatewayJob::Find { gateway, exact } => { // findExitPortalXZPosTentative over the loaded chunks. let dir = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero(); @@ -947,8 +1001,11 @@ impl Game<'_> { let exit = [tallest[0], tallest[1] + 10, tallest[2]]; self.place_gateway(exit)?; self.set_gateway_exit(exit, gateway, false)?; - self.set_gateway_exit(gateway, exit, false)?; - Ok(bottom_center(find_exit(self, exit))) + // setExitPosition keeps the gateway's own exactTeleport. + self.set_gateway_exit(gateway, exit, exact)?; + Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))) } } } @@ -1245,3 +1302,79 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::containers::EndGateway; + + #[test] + fn a_new_exit_keeps_the_gateways_exact_teleport() { + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + let plain = BlockEntity::EndGateway(EndGateway::default()); + assert!(exact_teleport(Some(&exact))); + assert!(!exact_teleport(Some(&plain))); + assert!(!exact_teleport(None)); + assert!(!exact_teleport(Some(&BlockEntity::DaylightDetector))); + let exit = [8, 100, 0]; + // Exact: the exit itself, nothing is searched for. + assert_eq!(exit_target(exit, true, |_| panic!("searched")), exit); + assert_eq!( + exit_target(exit, false, |e| [e[0], e[1] + 11, e[2]]), + [8, 111, 0] + ); + } + + #[test] + fn end_gateway_job_prefers_block_entity_then_legacy_then_heuristic() { + let gateway = [702, 100, 0]; + let exit = [8, 100, 0]; + for exact in [true, false] { + let entity = BlockEntity::EndGateway(EndGateway { + exit_portal: Some(exit), + exact_teleport: exact, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(gateway, Some(&entity), Some((END_SPAWN, !exact))), + GatewayJob::Known { exit, exact }, + ); + } + let empty = BlockEntity::EndGateway(EndGateway::default()); + for entity in [None, Some(&empty)] { + assert_eq!( + GatewayJob::for_gateway(gateway, entity, Some((exit, false))), + GatewayJob::Known { exit, exact: false } + ); + assert_eq!( + GatewayJob::for_gateway(gateway, entity, None), + GatewayJob::Known { + exit: END_SPAWN, + exact: true + } + ); + let nearby = [96, 75, 0]; + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(nearby, Some(&exact), None), + GatewayJob::Find { + gateway: nearby, + exact: true + } + ); + assert_eq!( + GatewayJob::for_gateway(nearby, entity, None), + GatewayJob::Find { + gateway: nearby, + exact: false + } + ); + } + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 5431adcd6..d398a2ac1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -643,6 +643,16 @@ pub fn encode_block_entity( entries.push(("custom_name", name.clone())); } } + // TheEndGatewayBlockEntity.saveAdditional. + BlockEntity::EndGateway(g) => { + entries.push(("Age", Tag::Long(g.age))); + if let Some(exit) = g.exit_portal { + entries.push(("exit_portal", Tag::IntArray(exit.to_vec()))); + } + if g.exact_teleport { + entries.push(("ExactTeleport", Tag::Byte(1))); + } + } BlockEntity::Spawner(s) => entries.extend(s.save()), BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Vault(v) => entries.extend(v.save()), @@ -702,11 +712,24 @@ fn roll_loaded_loot( biome, )) } +/// `TheEndGatewayBlockEntity.loadAdditional`. +pub fn decode_end_gateway(tag: &Tag) -> crate::containers::EndGateway { + crate::containers::EndGateway { + age: number(tag.get("Age")).unwrap_or(0), + exit_portal: tag + .get("exit_portal") + .and_then(crate::block_entity_nbt::gateway_exit), + exact_teleport: number(tag.get("ExactTeleport")).unwrap_or(0) != 0, + } +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); let id = text(tag.get("id"))?; let pos = (int("x")?, int("y")?, int("z")?); + if id == "minecraft:end_gateway" { + return Some((pos, BlockEntity::EndGateway(decode_end_gateway(tag)))); + } if id == "minecraft:jukebox" { let record = tag.get("RecordItem").and_then(item_from_nbt); let ticks = number(tag.get("ticks_since_song_started")).unwrap_or(0); @@ -846,6 +869,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Lectern(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), @@ -4660,6 +4684,79 @@ mod tests { } use super::*; + #[test] + fn end_gateway_block_entity_round_trips() { + use crate::containers::{BlockEntity, EndGateway}; + let plain = BlockEntity::for_block("minecraft:end_gateway").expect("gateway"); + assert!(matches!(&plain, BlockEntity::EndGateway(g) if *g == EndGateway::default())); + for exit in [None, Some([8, 100, 0])] { + for exact in [false, true] { + let gateway = EndGateway { + age: 201, + exit_portal: exit, + exact_teleport: exact, + }; + let tag = encode_block_entity( + (702, 100, 0), + &BlockEntity::EndGateway(gateway.clone()), + "minecraft:end_gateway", + ); + assert_eq!( + text(tag.get("id")).as_deref(), + Some("minecraft:end_gateway") + ); + assert_eq!(tag.get("Age"), Some(&Tag::Long(201))); + assert_eq!( + tag.get("exit_portal"), + exit.map(|p| Tag::IntArray(p.to_vec())).as_ref() + ); + assert_eq!( + tag.get("ExactTeleport"), + exact.then_some(Tag::Byte(1)).as_ref() + ); + let (pos, back) = decode_block_entity(&tag).expect("gateway"); + assert_eq!(pos, (702, 100, 0)); + assert!(matches!(back, BlockEntity::EndGateway(g) if g == gateway)); + } + } + } + + #[test] + fn end_gateway_exit_requires_spawnable_bounds() { + for (exit, valid) in [ + (vec![-30_000_000, -20_000_000, -30_000_000], true), + (vec![29_999_999, 19_999_999, 29_999_999], true), + (vec![30_000_000, 0, 0], false), + (vec![0, 0, 30_000_000], false), + (vec![-30_000_001, 0, 0], false), + (vec![0, 0, -30_000_001], false), + (vec![0, 20_000_000, 0], false), + (vec![0, -20_000_001, 0], false), + (vec![i32::MIN, 0, 0], false), + (vec![0, 100], false), + ] { + let tag = Tag::compound([ + ("id", string("minecraft:end_gateway")), + ("x", Tag::Int(702)), + ("y", Tag::Int(100)), + ("z", Tag::Int(0)), + ("exit_portal", Tag::IntArray(exit)), + ]); + let (_, crate::containers::BlockEntity::EndGateway(g)) = + decode_block_entity(&tag).unwrap() + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal.is_some(), valid); + let canonical = crate::block_entity_nbt::canonical(&tag).expect("gateway NBT"); + assert_eq!(canonical.get("exit_portal").is_some(), valid); + } + assert_eq!( + decode_end_gateway(&Tag::Compound(Compound::new())), + crate::containers::EndGateway::default() + ); + } + #[test] fn skull_block_entity_keeps_its_profile() { // A placed `player_head` as vanilla saves it: the owning player's diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 604cf7925..45eccbac7 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -199,6 +199,9 @@ fn generated_block_entity(block: &str, nbt: &Compound) -> Option { BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())), // BannerBlockEntity.loadAdditional: the End cities' black triangles. BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())), + BlockEntity::EndGateway(g) => { + *g = crate::save::decode_end_gateway(&Tag::Compound(nbt.clone())) + } _ => {} } Some(entity) @@ -242,6 +245,23 @@ mod tests { use super::*; use horizon_world::loot::{ExplorationMap, LootStack}; + #[test] + fn generated_end_gateway_keeps_its_exit() { + let Tag::Compound(nbt) = Tag::compound([ + ("exit_portal", Tag::IntArray(vec![100, 50, 0])), + ("ExactTeleport", Tag::Byte(1)), + ]) else { + unreachable!() + }; + let Some(BlockEntity::EndGateway(g)) = + generated_block_entity("minecraft:end_gateway", &nbt) + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal, Some([100, 50, 0])); + assert!(g.exact_teleport); + } + #[test] fn placed_chest_loot_keeps_its_enchantments_and_potions() { let stack = From b90f9ec1efc6ed34d815ad8652c5accab5600c73 Mon Sep 17 00:00:00 2001 From: Carlos Nunez Date: Mon, 26 Oct 2026 16:57:07 -0400 Subject: [PATCH 2/2] Make an End gateway's block entity the source of its exit The side file kept an entry for a gateway after Horizon created its exit, so removing the exit with /data remove block ... exit_portal, or placing a different gateway there, sent the player to the old exit again. Once the gateway's chunk is loaded, gateway_job moves an entry the side file still holds into the block entity (unless the block entity has an exit of its own) and drops the entry. set_gateway_exit writes only the block entity when the chunk is loaded, and leaves an entry in the side file only when the chunk is already unloaded. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/end.rs | 97 +++++++++++++++++++++------ 1 file changed, 78 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index e8b9a96e3..687ba6bb4 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -5,7 +5,7 @@ use super::{Dim, Game}; use horizon_client::{ Result, - containers::BlockEntity, + containers::{BlockEntity, EndGateway}, environment::Environment, items::ItemStack, mesher::Vertex, @@ -69,6 +69,17 @@ fn exact_teleport(entity: Option<&BlockEntity>) -> bool { matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport) } +/// Moves an exit that only the side file knew into the gateway's block entity, unless the block +/// entity has its own; true when it took the saved one. +fn adopt_saved_exit(entity: &mut EndGateway, (exit, exact): ([i32; 3], bool)) -> bool { + if entity.exit_portal.is_some() { + return false; + } + entity.exit_portal = Some(exit); + entity.exact_teleport = exact; + true +} + /// The end of `getPortalPosition`: the exit itself when the teleport is exact, /// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`). fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] { @@ -820,23 +831,7 @@ impl Game<'_> { self.end.exits.as_mut().expect("loaded exits") } - fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { - // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). - let key = (gateway[0], gateway[1], gateway[2]); - let chunk = (gateway[0] >> 4, gateway[2] >> 4); - // The gateway's chunk can be unloaded by now (travel waits for the destination): the - // side map below still records the exit. - if self.world.chunks.contains_key(&chunk) - && let BlockEntity::EndGateway(g) = self - .world - .block_entities - .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) - { - g.exit_portal = Some(exit); - g.exact_teleport = exact; - self.world.modified.insert(chunk); - } - self.gateway_exits().insert(gateway, (exit, exact)); + fn save_gateway_exits(&mut self) -> Result<()> { let list: Vec<_> = self .gateway_exits() .iter() @@ -848,6 +843,35 @@ impl Game<'_> { Ok(()) } + /// Drops a gateway's entry from the side file: its block entity is the source of truth. + fn forget_gateway_exit(&mut self, gateway: [i32; 3]) -> Result<()> { + if self.gateway_exits().remove(&gateway).is_some() { + self.save_gateway_exits()?; + } + Ok(()) + } + + fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { + // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + // The gateway's chunk can be unloaded by now (travel waits for the destination): the + // exit then waits in the side file until the gateway is used again (`gateway_job`). + if self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + g.exit_portal = Some(exit); + g.exact_teleport = exact; + self.world.modified.insert(chunk); + return self.forget_gateway_exit(gateway); + } + self.gateway_exits().insert(gateway, (exit, exact)); + self.save_gateway_exits() + } + /// EndGatewayBlock.entityInside and TheEndGatewayBlockEntity.getPortalPosition: /// travel within the End, waiting for the destination chunks to load. fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> { @@ -867,7 +891,25 @@ impl Game<'_> { /// its exit, or the search for one, and the spot to load before either /// is resolved ([`Game::resolve_gateway`]). pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { - let known = self.gateway_exits().get(&gateway).copied(); + let mut known = self.gateway_exits().get(&gateway).copied(); + // Once the gateway's chunk is loaded its block entity is the source of truth: an exit the + // side file kept for it moves there, and the entry is dropped, so removing or replacing + // the exit (`/data remove block`) is not undone by an old entry. + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + if let Some(saved) = known + && self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + if adopt_saved_exit(g, saved) { + self.world.modified.insert(chunk); + } + known = None; + let _ = self.forget_gateway_exit(gateway); + } let job = GatewayJob::for_gateway( gateway, self.world @@ -1308,6 +1350,23 @@ mod tests { use super::*; use horizon_client::containers::EndGateway; + #[test] + fn a_saved_exit_moves_into_a_gateway_without_one() { + let saved = ([8, 100, 0], true); + let mut bare = EndGateway::default(); + assert!(adopt_saved_exit(&mut bare, saved)); + assert_eq!(bare.exit_portal, Some([8, 100, 0])); + assert!(bare.exact_teleport); + // The block entity's own exit wins over a stale entry. + let mut own = EndGateway { + exit_portal: Some([1, 2, 3]), + ..Default::default() + }; + assert!(!adopt_saved_exit(&mut own, saved)); + assert_eq!(own.exit_portal, Some([1, 2, 3])); + assert!(!own.exact_teleport); + } + #[test] fn a_new_exit_keeps_the_gateways_exact_teleport() { let exact = BlockEntity::EndGateway(EndGateway {