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) <noreply@openai.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Carlos Nunez
2026-10-26 16:36:53 -04:00
parent e704a8dccb
commit 951b88a3c2
7 changed files with 302 additions and 28 deletions
+11 -4
View File
@@ -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<Tag> {
}
"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));
}
+16
View File
@@ -98,10 +98,19 @@ pub enum BlockEntity {
Campfire(Box<Campfire>),
/// `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,
+2
View File
@@ -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(_),
+1 -2
View File
@@ -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
+155 -22
View File
@@ -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
}
);
}
}
}
+97
View File
@@ -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
@@ -199,6 +199,9 @@ fn generated_block_entity(block: &str, nbt: &Compound) -> Option<BlockEntity> {
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 =