Merge remote-tracking branch 'origin/main' into fix/server-air-absorption

# Conflicts:
#	tools/lan_e2e.py
This commit is contained in:
Ludovic Marie
2026-10-23 07:45:28 +02:00
35 changed files with 2610 additions and 379 deletions
+23
View File
@@ -167,6 +167,7 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
style.underlined = flag("underlined");
style.strikethrough = flag("strikethrough");
style.obfuscated = flag("obfuscated");
style.font = o.get("font").and_then(crate::text::font_id);
style
}
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
@@ -266,4 +267,26 @@ mod tests {
let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap();
assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab");
}
#[test]
fn the_font_is_inherited_and_kept() {
let (v, _) =
parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#)
.unwrap();
let t = to_text(&v, &mut |_| Text::empty());
let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect();
let (alt, uniform) = (
Some("minecraft:alt".into()),
Some("minecraft:uniform".into()),
);
assert_eq!(fonts, [alt.clone(), alt, uniform]);
// Back to JSON with the field, which a re-read keeps.
let again = to_text(&t.component(), &mut |_| Text::empty());
let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect();
assert_eq!(kept, fonts);
// Not an identifier: no font.
let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap();
let t = to_text(&v, &mut |_| Text::empty());
assert_eq!(t.spans[0].style.font, None);
}
}
File diff suppressed because it is too large Load Diff
+34 -18
View File
@@ -162,6 +162,7 @@ mod ui_control;
mod vault;
mod villagers;
mod wandering_trader;
mod win;
mod wind;
mod wither;
mod world_loading;
@@ -464,6 +465,8 @@ enum Screen {
Friends,
/// CommandBlockEditScreen (game/command_blocks.rs).
CommandBlock,
/// WinScreen: the end poem and the credits (game/win.rs).
Win,
}
struct Mining {
pos: [i32; 3],
@@ -1357,6 +1360,8 @@ struct Game<'a> {
respawn_travel: Option<respawn_anchor::RespawnConfig>,
/// The next enter_dimension call comes from an End portal.
end_portal_travel: bool,
/// The open WinScreen (game/win.rs).
win: Option<win::Win>,
end: end::EndState,
block_ticks: Ticks,
tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership,
@@ -3798,6 +3803,9 @@ impl Game<'_> {
return Ok(());
}
if let Some((_, target)) = &self.travelling {
if self.win_screen_holds_arrival() {
return Ok(());
}
let (cx, cz) = (
(target.x.floor() as i32) >> 4,
(target.z.floor() as i32) >> 4,
@@ -4485,7 +4493,8 @@ impl Game<'_> {
| Screen::WorldOptions
| Screen::Friends
| Screen::CommandBlock
) || self.book.is_some())
) || self.book.is_some()
|| self.win_screen_pauses())
}
/// `MouseHandler.grabMouse` / `releaseMouse`. Both put the pointer at
/// the window's centre, so a screen opened from gameplay (inventory,
@@ -4700,6 +4709,10 @@ impl Game<'_> {
fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = HudBatch::new(size);
let (w, h) = (batch.width, batch.height);
if self.screen == Screen::Win {
self.draw_win_screen(&mut batch);
return batch;
}
if self.screen == Screen::Options {
self.draw_options(&mut batch);
return batch;
@@ -4934,7 +4947,7 @@ impl Game<'_> {
self.draw_creative(&mut batch);
}
Screen::Chat => self.draw_chat_screen(&mut batch),
Screen::Playing | Screen::Options => {}
Screen::Playing | Screen::Options | Screen::Win => {}
}
self.draw_toasts(&mut batch);
self.remote_hud(&mut batch);
@@ -7519,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;
@@ -9506,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;
@@ -10099,12 +10105,13 @@ impl Game<'_> {
let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
let blurred = loading
|| self.title.as_ref().is_some_and(|t| {
self.screen == Screen::Options
matches!(self.screen, Screen::Options | Screen::Win)
|| !matches!(t.mode, horizon_client::title::Mode::Main)
})
|| (self.title.is_none()
&& self.player.is_some()
&& self.screen.blurs_background(self.pause_menu));
&& (self.screen.blurs_background(self.pause_menu)
|| (self.screen == Screen::Win && self.win_screen_pauses())));
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
}
@@ -10188,6 +10195,7 @@ impl Game<'_> {
Screen::WorldOptions => self.world_options_escape(),
Screen::CommandBlock => self.close_command_block(),
Screen::Chat => self.close_chat(),
Screen::Win => self.close_win_screen()?,
},
KeyCode::Digit1
| KeyCode::Digit2
@@ -10787,7 +10795,9 @@ impl ApplicationHandler for Game<'_> {
}) * wheel_sensitivity
};
let d = scaled(raw_y) as f32;
if let Some(title) = &mut self.title {
if let Some(title) = &mut self.title
&& self.screen != Screen::Win
{
let size = self
.window
.as_ref()
@@ -10845,6 +10855,7 @@ impl ApplicationHandler for Game<'_> {
self.advancements_scroll(scaled(raw_x) as f32, d);
}
}
WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {}
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
if self.options_waiting_for_key() && state == ElementState::Pressed {
self.options_bind_mouse(button)?;
@@ -11101,6 +11112,9 @@ impl ApplicationHandler for Game<'_> {
{
self.world_options_key(&event)
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Win => {
self.win_key(&event)?
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::CommandBlock => {
self.command_block_key(&event)
}
@@ -11234,6 +11248,7 @@ impl ApplicationHandler for Game<'_> {
self.tick_ambience();
self.tick_fov();
}
self.tick_win_screen()?;
self.tick_music();
self.tick_sound_engine();
self.clock.record(started.elapsed());
@@ -11661,6 +11676,7 @@ impl<'a> Game<'a> {
respawn_config: None,
respawn_travel: None,
end_portal_travel: false,
win: None,
end: Default::default(),
block_ticks: Ticks::new(0),
tick_chunks: Default::default(),
+1
View File
@@ -405,6 +405,7 @@ impl Game<'_> {
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
}
}
pub(super) fn inventory_counts(&self) -> BTreeMap<String, i64> {
+35 -20
View File
@@ -294,6 +294,18 @@ impl Game<'_> {
}
// ---- entities -------------------------------------------------------
/// The level `t` is in (`Entity.level`): a server's players have their
/// own, which need not be the one in place; everything else is in the
/// level in place.
pub(super) fn target_level(&self, t: Target) -> Dim {
let conn = match t {
Target::Player => self.lan_acting,
Target::Guest(conn) => Some(conn),
_ => None,
};
conn.and_then(|c| self.command_guest(c))
.map_or(self.dim, |g| Dim::from_id(&g.dimension))
}
pub(super) fn target_position(&self, t: Target) -> Option<[f64; 3]> {
match t {
Target::Player => self
@@ -1191,15 +1203,12 @@ impl Game<'_> {
pos: [f64; 3],
rotation: Option<[f32; 2]>,
) -> bool {
let (conn, at) = match t {
Target::Player => (self.lan_acting, self.dim),
Target::Guest(conn) => (
Some(conn),
self.command_guest(conn)
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
),
_ => (None, self.dim),
let conn = match t {
Target::Player => self.lan_acting,
Target::Guest(conn) => Some(conn),
_ => None,
};
let at = self.target_level(t);
let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else {
return false;
};
@@ -1222,12 +1231,7 @@ impl Game<'_> {
let dest = self.entities(ctx, "destination", false)?[0];
let pos = self.target_position(dest).unwrap_or(self.source_position());
// Into the destination's level.
let level = match dest {
Target::Guest(conn) => self
.command_guest(conn)
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
_ => self.dim,
};
let level = self.target_level(dest);
// TeleportCommand.teleportToEntity: the destination's rotation too.
let rotation = Some(self.target_rotation(dest));
for &t in &targets {
@@ -2281,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![
@@ -155,14 +155,20 @@ impl Game<'_> {
_ => s.pos,
}
}
/// Evaluate `f` with `source` as the command source.
/// Evaluate `f` with `source` as the command source, in the source's
/// level (`CommandSourceStack.getLevel`): a server puts that level in
/// place for it.
pub(in crate::game) fn with_source<T>(
&mut self,
source: Source,
f: impl FnOnce(&mut Self) -> T,
) -> T {
let previous = self.command_source.replace(source);
let back = self.enter_command_level(source.dimension);
let out = f(self);
if let Some(back) = back {
self.enter_command_level(back);
}
self.command_source = previous;
out
}
@@ -447,11 +453,13 @@ impl Game<'_> {
"at" => targets(self)?
.into_iter()
.filter_map(|t| {
// CommandSourceStack.withLevel(entity.level()).
let level = self.target_level(t);
Some(Source {
pos: self.target_position(t)?,
rot: self.target_rotation(t),
dimension: self.dim,
level: None,
dimension: level,
level: (level != self.dim).then_some(level),
..s
})
})
+25
View File
@@ -42,6 +42,7 @@ const HELP: &[&str] = &[
"chat MESSAGE send chat or a /command to the server",
"disconnect leave the server for the server list",
"respawn respawn after death on a server",
"credits [poem] [SCROLL] roll the credits (with the end poem), or hold them SCROLL pixels in",
"quit save and exit",
];
@@ -574,6 +575,7 @@ impl Game<'_> {
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
"extras" => Page::Extras,
"credits" => Page::Credits,
"horizon" => Page::Horizon,
"agent" => Page::Agent,
"shader-packs" => Page::ShaderPacks,
@@ -652,6 +654,25 @@ impl Game<'_> {
self.connect_server(arg(1)?, &name)?;
ok()
}
"credits" => {
let poem = words.get(1) == Some(&"poem");
let hold = words
.get(1 + usize::from(poem))
.map(|s| s.parse::<f32>())
.transpose()?;
if self.screen != Screen::Win {
let finish = if self.screen == Screen::Options {
super::win::Finish::Options
} else {
super::win::Finish::Closed
};
self.open_win_screen(poem, finish);
}
if let Some(scroll) = hold {
self.hold_win_screen(scroll);
}
ok()
}
"respawn" => {
if self.remote.is_none() || self.screen != Screen::Dead {
return Err("respawn needs the death screen on a server".into());
@@ -734,6 +755,9 @@ impl Game<'_> {
}
fn screen_name(&self) -> &'static str {
if self.screen == Screen::Win {
return "win";
}
if self.title.is_some() {
return "title";
}
@@ -751,6 +775,7 @@ impl Game<'_> {
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
}
}
+21 -10
View File
@@ -23,7 +23,7 @@ const GATEWAY_FILE: &str = "horizon-end-gateways.json";
/// A gateway teleport waiting for its destination chunks.
#[derive(Clone, Copy, Debug)]
enum GatewayJob {
pub(super) enum GatewayJob {
/// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway.
Find { gateway: [i32; 3] },
/// A known exit (exact, or findExitPosition around it).
@@ -342,7 +342,10 @@ impl Game<'_> {
f64::from(p.dimensions.width),
f64::from(p.dimensions.height),
);
if portal {
if portal && self.dim == Dim::End && !self.level.seen_credits {
// EndPortalBlock.entityInside: the first exit shows the credits.
self.show_end_credits()?;
} else if portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
Dim::Overworld
@@ -700,6 +703,20 @@ impl Game<'_> {
fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> {
// TheEndGatewayBlockEntity.triggerCooldown: 40 ticks.
self.end.gateway_cooldown = 40;
let (job, destination) = self.gateway_job(gateway);
let Some(player) = self.player.take() else {
return Ok(());
};
self.end.job = Some(job);
self.end_travel = true;
self.travelling = Some((player, destination));
Ok(())
}
/// Where `gateway` leads (TheEndGatewayBlockEntity.getPortalPosition):
/// 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 job = match known {
Some((exit, exact)) => GatewayJob::Known { exit, exact },
@@ -725,13 +742,7 @@ impl Game<'_> {
Vec3::new(d.x, 75.0, d.y)
}
};
let Some(player) = self.player.take() else {
return Ok(());
};
self.end.job = Some(job);
self.end_travel = true;
self.travelling = Some((player, destination));
Ok(())
(job, destination)
}
fn chunk_empty(&self, x: f64, z: f64) -> Option<bool> {
@@ -768,7 +779,7 @@ impl Game<'_> {
/// The teleport position of a gateway job, creating the exit gateway (and
/// an island when the chunk has no landing spot) for new destinations.
fn resolve_gateway(&mut self, job: GatewayJob, target: Vec3) -> Result<Vec3> {
pub(super) fn resolve_gateway(&mut self, job: GatewayJob, target: Vec3) -> Result<Vec3> {
let bottom_center = |p: [i32; 3]| {
Vec3::new(
f64::from(p[0]) + 0.5,
+29 -1
View File
@@ -224,7 +224,7 @@ impl Game<'_> {
}
set.entries().map(|(k, _)| k.0).collect()
}
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT);
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT, minecarts);
/// the player takes `damage_type`.
/// `ServerExplosion.hurtEntities` for the player: damage scaled by
/// distance and exposure, through a raised shield (`hurtServer` blocks
@@ -460,6 +460,34 @@ impl Game<'_> {
);
}
self.tnts = tnts;
// Minecarts: VehicleEntity.hurtServer (explosions ignite TNT carts),
// then the push from their eyes (0.85 of their height).
let ids: Vec<u32> = self.carts.iter().map(|c| c.id).collect();
for id in ids {
let Some(i) = self.carts.iter().position(|c| c.id == id) else {
continue;
};
let bounds = self.carts[i].bounds();
let feet = self.carts[i].position;
let dist = distance([feet.x, feet.y, feet.z]) / diameter;
if dist > 1.0 {
continue;
}
let (lo, hi) = (bounds.min_position(), bounds.max_position());
let exposure = self.seen_percent(center, [lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]);
self.hurt_cart(i, damage(dist, exposure), false, true);
let Some(c) = self.carts.iter_mut().find(|c| c.id == id) else {
continue;
};
let eye_height = f64::from((hi.y - lo.y) as f32 * 0.85f32);
let dir = direction([feet.x, feet.y + eye_height, feet.z]);
let power = (1.0 - dist) * f64::from(exposure);
c.velocity = Vec3::new(
c.velocity.x + dir[0] * power,
c.velocity.y + dir[1] * power,
c.velocity.z + dir[2] * power,
);
}
}
/// `Level.explode` on the server: positions, entities, blocks, fire; then
/// the client's explosion sound.
+32 -11
View File
@@ -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,
@@ -315,6 +315,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.
@@ -476,7 +477,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);
@@ -513,6 +515,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 {
@@ -1492,17 +1495,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;
@@ -1541,6 +1559,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());
}
+18
View File
@@ -253,6 +253,24 @@ impl Game<'_> {
Ok(())
}
/// Put `dim`'s level in place for a command whose source is there
/// (`execute in`, `execute at` a player in another level), opening it if
/// nobody is in it; returns the level to put back afterwards. Only a
/// server holds other levels.
pub(super) fn enter_command_level(&mut self, dim: Dim) -> Option<Dim> {
if self.options.dedicated.is_none() || dim == self.dim {
return None;
}
let back = self.dim;
match self.enter_level(None, dim) {
Ok(()) => Some(back),
Err(e) => {
log::error!("could not open {}: {e}", dim.id());
None
}
}
}
/// 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
+89 -60
View File
@@ -16,7 +16,7 @@ use horizon_client::{
sound_engine::{CartSound, SoundEngine, SoundInstance, Sounds},
};
use horizon_core::{
geometry::{Aabb, Vec3},
geometry::{Aabb, Vec3, trig},
random::RandomSource,
};
use horizon_world::registry::BlockStateId;
@@ -637,6 +637,9 @@ impl Game<'_> {
let r = self.world.random.next_double();
let power = (4.0 + r * 1.5 * speed) as f32;
let at = [c.position.x, c.position.y, c.position.z];
// The cart is the explosion's source: it is gone before the blast
// looks for entities, so it can't hit itself.
self.carts.retain(|x| x.id != c.id);
let _ = self.server_explode(at, power, BlockInteraction::Destroy, false);
}
/// `MinecartHopper.suckInItems`: items above, into the five slots.
@@ -683,8 +686,7 @@ impl Game<'_> {
}
}
}
/// `AbstractMinecart.push(player)` when the player walks into a cart,
/// and carts pushing each other (`pushOtherMinecart`).
/// `AbstractMinecart.push(player)` when the player walks into a cart.
fn push_carts(&mut self) {
let player = self.player.as_ref().map(|p| p.position);
let riding = self.riding;
@@ -719,55 +721,71 @@ impl Game<'_> {
}
}
}
for j in i + 1..self.carts.len() {
let (a, b) = (&self.carts[i], &self.carts[j]);
if !a
.bounds()
.inflate(Vec3::new(0.2, 0.0, 0.2))
.intersects(b.bounds())
{
continue;
}
let (mut xa, mut za) = (b.position.x - a.position.x, b.position.z - a.position.z);
let dd = xa * xa + za * za;
if dd < 1.0e-4 {
continue;
}
let d = dd.sqrt();
let pow = (1.0 / d).min(1.0);
xa = xa / d * pow * f64::from(0.1f32) * 0.5;
za = za / d * pow * f64::from(0.1f32) * 0.5;
let dir =
glam::DVec2::new(b.position.x - a.position.x, b.position.z - a.position.z)
.normalize_or_zero();
let r = a.yaw.to_radians();
let facing =
glam::DVec2::new(f64::from(r.cos()), f64::from(r.sin())).normalize_or_zero();
if dir.dot(facing).abs() < f64::from(0.8f32) {
continue;
}
let (ma, mb) = (a.velocity, b.velocity);
let (fa, fb) = (a.kind == CartKind::Furnace, b.kind == CartKind::Furnace);
let (na, nb) = if fb && !fa {
(
Vec3::new(ma.x * 0.2 + mb.x - xa, ma.y, ma.z * 0.2 + mb.z - za),
Vec3::new(mb.x * 0.95, mb.y, mb.z * 0.95),
)
} else if fa && !fb {
(
Vec3::new(ma.x * 0.95, ma.y, ma.z * 0.95),
Vec3::new(mb.x * 0.2 + ma.x + xa, mb.y, mb.z * 0.2 + ma.z + za),
)
} else {
let (xdd, zdd) = ((mb.x + ma.x) / 2.0, (mb.z + ma.z) / 2.0);
(
Vec3::new(ma.x * 0.2 + xdd - xa, ma.y, ma.z * 0.2 + zdd - za),
Vec3::new(mb.x * 0.2 + xdd + xa, mb.y, mb.z * 0.2 + zdd + za),
)
};
self.carts[i].velocity = na;
self.carts[j].velocity = nb;
}
}
/// `OldMinecartBehavior.pushAndPickupEntities` for carts, at the end of
/// cart `i`'s own tick: each other cart in its box (0.2 wider on each
/// side) gets `push(cart i)`. Running it per cart, after that cart moved
/// and before the next one does, is what splits stacked carts apart.
fn push_from_cart(&mut self, i: usize) {
let reach = f64::from(0.2f32);
let hitbox = self.carts[i].bounds().inflate(Vec3::new(reach, 0.0, reach));
for j in 0..self.carts.len() {
if j == i || !hitbox.intersects(self.carts[j].bounds()) {
continue;
}
// AbstractMinecart.push(entity): `this` is cart j, `entity` cart i.
let (this, other) = (&self.carts[j], &self.carts[i]);
let (mut xa, mut za) = (
other.position.x - this.position.x,
other.position.z - this.position.z,
);
let dd = xa * xa + za * za;
if dd < f64::from(1.0e-4f32) {
continue;
}
let d = dd.sqrt();
xa /= d;
za /= d;
let pow = (1.0 / d).min(1.0);
xa = xa * pow * f64::from(0.1f32) * 0.5;
za = za * pow * f64::from(0.1f32) * 0.5;
// pushOtherMinecart (old movement): only along this cart's facing.
let dir = glam::DVec2::new(
other.position.x - this.position.x,
other.position.z - this.position.z,
)
.normalize_or_zero();
let r = f64::from(this.yaw * 0.017453292f32);
let facing = glam::DVec2::new(f64::from(trig::cos(r)), f64::from(trig::sin(r)))
.normalize_or_zero();
if dir.dot(facing).abs() < f64::from(0.8f32) {
continue;
}
let (mt, mo) = (this.velocity, other.velocity);
let (ft, fo) = (
this.kind == CartKind::Furnace,
other.kind == CartKind::Furnace,
);
let (nt, no) = if fo && !ft {
(
Vec3::new(mt.x * 0.2 + (mo.x - xa), mt.y, mt.z * 0.2 + (mo.z - za)),
Vec3::new(mo.x * 0.95, mo.y, mo.z * 0.95),
)
} else if !fo && ft {
(
Vec3::new(mt.x * 0.95, mt.y, mt.z * 0.95),
Vec3::new(mo.x * 0.2 + (mt.x + xa), mo.y, mo.z * 0.2 + (mt.z + za)),
)
} else {
let (xdd, zdd) = ((mo.x + mt.x) / 2.0, (mo.z + mt.z) / 2.0);
(
Vec3::new(mt.x * 0.2 + (xdd - xa), mt.y, mt.z * 0.2 + (zdd - za)),
Vec3::new(mo.x * 0.2 + (xdd + xa), mo.y, mo.z * 0.2 + (zdd + za)),
)
};
self.carts[j].velocity = nt;
self.carts[i].velocity = no;
}
}
/// Every cart but the ridden one (which ticks with its rider).
@@ -777,14 +795,17 @@ impl Game<'_> {
let ticking = self.entity_ticking_area();
// A server player's minecart moves with its rider (lan_vehicles.rs).
let ridden = self.guest_vehicles();
let mut i = 0;
while i < self.carts.len() {
// By id: an exploding cart can destroy or prime others mid-loop.
let ids: Vec<u32> = self.carts.iter().map(|c| c.id).collect();
for id in ids {
let Some(i) = self.carts.iter().position(|c| c.id == id) else {
continue;
};
let p = self.carts[i].position;
if Some(self.carts[i].id) == self.riding
|| ridden.contains(&self.carts[i].id)
if Some(id) == self.riding
|| ridden.contains(&id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
i += 1;
continue;
}
let mut c = self.carts[i].clone();
@@ -792,9 +813,12 @@ impl Game<'_> {
if c.kind == CartKind::Hopper {
self.hopper_cart_pickup(&mut c);
}
let Some(i) = self.carts.iter().position(|c| c.id == id) else {
continue;
};
if alive {
self.carts[i] = c;
i += 1;
self.push_from_cart(i);
} else {
self.carts.remove(i);
}
@@ -865,8 +889,13 @@ impl Game<'_> {
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
let Some(i) = self.carts.iter().position(|x| x.id == c.id) else {
self.riding = None;
return true;
};
if alive {
self.carts[i] = c;
self.push_from_cart(i);
} else {
self.carts.remove(i);
self.riding = None;
@@ -1121,8 +1150,8 @@ impl Game<'_> {
}
/// `VehicleEntity.hurtServer`: shake, add the damage, break past 40 (at
/// once for creative players); TNT minecarts prime instead when moving
/// or hurt by fire.
fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) {
/// or hurt by fire or an explosion (`damageSourceIgnitesTnt`).
pub(super) fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) {
let c = &mut self.carts[i];
c.hurt_dir = -c.hurt_dir;
c.hurt_time = 10;
@@ -1131,7 +1160,7 @@ impl Game<'_> {
if destroyed {
let mut c = self.carts.remove(i);
let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z;
if c.kind == CartKind::Tnt && (fire || speed >= 0.01) {
if c.kind == CartKind::Tnt && (fire || speed >= f64::from(0.01f32)) {
// MinecartTNT.destroy: prime instead of breaking.
if c.fuse < 0 {
self.prime_cart(&mut c);
+6 -2
View File
@@ -12,7 +12,7 @@ impl Game<'_> {
pub(super) fn tick_music(&mut self) {
let (music, volume) = self.situational_music();
// LevelLoadingScreen: no new track before the player is in the world.
let loading = self.title.is_none() && self.player.is_none();
let loading = self.title.is_none() && self.player.is_none() && self.win.is_none();
self.music
.tick(music.as_ref(), volume, loading, &mut self.audio);
}
@@ -59,7 +59,11 @@ impl Game<'_> {
None => (empty, 1.0),
};
let situation = Situation {
screen_music: None,
// WinScreen.getBackgroundMusic.
screen_music: self
.win
.is_some()
.then(horizon_client::music::Music::credits),
in_world: eye.is_some(),
in_end: self.dim == super::Dim::End,
boss_music: self.boss_music(),
@@ -242,6 +242,7 @@ impl Game<'_> {
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
}
}
Ok(())
+4
View File
@@ -2133,6 +2133,10 @@ impl Game<'_> {
);
}
}
// WIN_GAME: the poem and credits, then PERFORM_RESPAWN.
4 if self.screen != Screen::Win => {
self.open_win_screen(true, super::win::Finish::RemoteRespawn);
}
1 => {
self.world.weather.raining = true;
self.world.weather.rain_level = (0.0, 0.0);
@@ -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<Vec3> {
@@ -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
@@ -25,6 +25,9 @@ impl Screen {
| Self::Inventory
| Self::Dead
| Self::CommandBlock => false,
// WinScreen.extractBackground: the poem fills the screen with the End portal, the
// credits alone blur. Game::menu_blur knows which one rolls.
Self::Win => false,
}
}
}
@@ -359,6 +362,7 @@ mod tests {
Screen::Inventory,
Screen::Dead,
Screen::CommandBlock,
Screen::Win,
] {
assert!(!screen.blurs_background(true));
assert!(!screen.blurs_background(false));
+129 -3
View File
@@ -7,9 +7,11 @@
//! another level: a Respawn packet keeping all data, then a teleport to the
//! exit once the destination has loaded around them.
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
@@ -22,6 +24,12 @@ pub(super) struct Trip {
end: bool,
/// The Nether portal plan, whose exit is found or built on arrival.
plan: Option<Plan>,
/// Through an End gateway, within the level: its exit, found or built
/// on arrival.
gateway: Option<GatewayJob>,
/// A respawn at this point outside the Overworld, resolved through its
/// block on arrival.
respawn: Option<RespawnConfig>,
/// Sent by a command: the player is already where it goes.
placed: bool,
}
@@ -95,7 +103,7 @@ impl Game<'_> {
if let Some(pos) = self.nether_portal_inside(at) {
self.portals.player.set_inside(pos, PLAYER_DELAY);
}
let (end_portal, _) = self.inside_end_portals(at, WIDTH, HEIGHT);
let (end_portal, gateway) = self.inside_end_portals(at, WIDTH, HEIGHT);
if end_portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
@@ -109,6 +117,19 @@ impl Game<'_> {
self.portals.player.cooldown = 10;
return;
}
// EndGatewayBlock.entityInside: a gateway that is not cooling down
// takes the player at once (no transition time) and cools down
// (triggerCooldown), even for a player still on its own cooldown.
if let Some(g) = gateway
&& self.gateway_enter(g)
{
if self.portals.player.cooldown == 0 {
self.start_gateway_trip(host, conn, g);
}
// setPortalCooldown: after the trip, or again while cooling down.
self.portals.player.cooldown = 10;
return;
}
let rule = if invulnerable {
"players_nether_portal_creative_delay"
} else {
@@ -197,6 +218,8 @@ impl Game<'_> {
target: destination,
end,
plan,
gateway: None,
respawn: None,
placed: false,
});
if let Err(e) = self.enter_level(Some(host), source) {
@@ -204,6 +227,91 @@ 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
/// waits there (its exit is found among those blocks, or built).
fn start_gateway_trip(&mut self, host: &mut LanHost, conn: u32, gateway: [i32; 3]) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let (job, destination) = self.gateway_job(gateway);
let at = [destination.x, destination.y, destination.z];
// Relative.union(DELTA, ROTATION).
host.hub.teleport_keeping_motion(i, at);
if let GatewayJob::Known { exact: true, .. } = job {
return;
}
self.server_trips.push(Trip {
conn,
dim: self.dim,
target: destination,
end: false,
plan: None,
gateway: Some(job),
respawn: None,
placed: false,
});
}
/// 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.
@@ -232,7 +340,23 @@ impl Game<'_> {
}
self.resolve_arrivals();
let yaw = host.hub.guests[i].yaw;
let (position, yaw) = if trip.end {
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) => {
log::error!("End gateway exit: {e}");
(trip.target, yaw)
}
}
} else if trip.end {
match self.end_arrival(trip.target) {
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
Err(e) => {
@@ -293,6 +417,8 @@ impl Game<'_> {
target: Vec3::new(t.at[0], t.at[1], t.at[2]),
end: false,
plan: None,
gateway: None,
respawn: None,
placed: true,
});
if let Err(e) = self.enter_level(Some(host), source) {
@@ -12,6 +12,8 @@ pub(super) struct StartupMenu {
title: Option<Title>,
options: OptionsUi,
options_open: bool,
/// The credits from Credits & Attribution, and their last frame.
win: Option<(horizon_client::win_screen::WinScreen, Instant)>,
root: PathBuf,
cursor: (f32, f32),
pointer: (f64, f64),
@@ -370,6 +372,21 @@ impl Loading {
let _ = std::fs::create_dir_all(&dir);
packs::open_folder(&dir);
}
Event::Credits => {
if let Some(gui) = &self.gui {
let name = self.options.as_ref().map_or_else(
|| horizon_client::offline_name::generate(0),
Options::player_name,
);
let screen = horizon_client::win_screen::WinScreen::new(
false,
&self.menu.root,
&name,
&gui.atlas.font,
);
self.menu.win = Some((screen, Instant::now()));
}
}
// The startup menu runs before the game opens a control socket.
Event::ButtonClick | Event::CopyAgentDetails => {}
}
@@ -457,6 +474,20 @@ impl Loading {
}
}
_ if self.gui.is_none() || self.menu.pending.is_some() => {}
WindowEvent::KeyboardInput { event, .. } if self.menu.win.is_some() => {
if let PhysicalKey::Code(code) = event.physical_key {
let pressed = event.state == ElementState::Pressed;
if code == KeyCode::Escape && pressed {
self.menu.win = None;
} else if let Some(key) = horizon_client::win_screen::Key::from_code(code)
&& let Some((win, _)) = &mut self.menu.win
{
win.key(key, pressed);
}
}
}
WindowEvent::MouseInput { .. } | WindowEvent::MouseWheel { .. }
if self.menu.win.is_some() => {}
WindowEvent::CursorMoved { position, .. } => {
self.menu.pointer = (position.x, position.y);
self.update_menu_cursor();
@@ -576,6 +607,15 @@ impl Loading {
self.progress.line(),
self.progress.fraction(),
);
} else if let Some((win, frame)) = &mut self.menu.win {
let now = Instant::now();
// 20 ticks a second: the startup menu runs no tick rate.
let delta_ticks = now.duration_since(*frame).as_secs_f32() * 20.0;
*frame = now;
win.draw(batch, &gui.atlas, delta_ticks, Default::default());
if win.finished(batch.height) {
self.menu.win = None;
}
} else if self.menu.options_open {
self.menu
.options
+150
View File
@@ -0,0 +1,150 @@
//! `WinScreen` in the game: the poem and credits after leaving the End for
//! the first time (`EndPortalBlock.entityInside` -> `ServerPlayer.showEndCredits`,
//! or a server's `WIN_GAME` event), and the credits from Credits &
//! Attribution.
use super::{Game, Screen};
use horizon_client::{
Result,
hud::{EndPortalFill, HudBatch},
win_screen::{Key, WinScreen},
};
use std::time::Instant;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
};
/// What closing the screen does (`WinScreen.onFinished`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Finish {
/// `PERFORM_RESPAWN` in single player: the player, out of the End since
/// the credits began, arrives in the Overworld.
Respawn,
/// `PERFORM_RESPAWN` sent to the server.
RemoteRespawn,
/// Back to Credits & Attribution.
Options,
/// Back to the game (`horizon-ctl credits`).
Closed,
}
pub(super) struct Win {
screen: WinScreen,
finish: Finish,
/// The last drawn frame, for the scroll's game-time delta.
frame: Instant,
}
impl Game<'_> {
pub(super) fn open_win_screen(&mut self, poem: bool, finish: Finish) {
let screen = WinScreen::new(
poem,
&self.options.resources,
&self.options.player_name(),
&self.gui.atlas.font,
);
self.win = Some(Win {
screen,
finish,
frame: Instant::now(),
});
self.keys.clear();
self.screen = Screen::Win;
self.capture(false);
}
/// `ServerPlayer.showEndCredits`: the player leaves the End now (no
/// longer in any level until the credits end) and has seen the credits.
pub(super) fn show_end_credits(&mut self) -> Result<()> {
self.level.seen_credits = true;
self.open_win_screen(true, Finish::Respawn);
self.end_portal_travel = true;
let result = self.enter_dimension(super::Dim::Overworld);
self.end_portal_travel = false;
result
}
/// Stop the scroll `scroll` pixels in (`horizon-ctl credits ... SCROLL`).
pub(super) fn hold_win_screen(&mut self, scroll: f32) {
if let Some(win) = self.win.as_mut() {
win.screen.hold(scroll);
}
}
/// `WinScreen.isPauseScreen`: only the credits without the poem pause.
pub(super) fn win_screen_pauses(&self) -> bool {
self.win.as_ref().is_some_and(|w| !w.screen.poem)
}
/// The player waits out of the world while the poem rolls.
pub(super) fn win_screen_holds_arrival(&self) -> bool {
self.win
.as_ref()
.is_some_and(|w| w.finish == Finish::Respawn)
}
pub(super) fn draw_win_screen(&mut self, batch: &mut HudBatch) {
let Some(win) = self.win.as_mut() else {
return;
};
let now = Instant::now();
// DeltaTracker.getGameTimeDeltaTicks: the frame's length in ticks.
let delta_ticks =
now.duration_since(win.frame).as_secs_f32() / self.clock.tick_duration().as_secs_f32();
win.frame = now;
let sprite = |n: &str| {
self.gui
.atlas
.sprites
.get(n)
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0])
};
let fill = EndPortalFill {
sprites: [
sprite("environment/end_sky"),
sprite("entity/end_portal/end_portal"),
],
game_time: (self.world.game_time % 24000) as f32 / 24000.0,
};
win.screen.draw(batch, &self.gui.atlas, delta_ticks, fill);
}
/// `WinScreen.keyPressed` / `keyReleased`; Escape closes it (`onClose`).
pub(super) fn win_key(&mut self, event: &KeyEvent) -> Result<()> {
let PhysicalKey::Code(code) = event.physical_key else {
return Ok(());
};
let pressed = event.state == ElementState::Pressed;
if code == KeyCode::Escape && pressed {
return self.close_win_screen();
}
let Some(key) = Key::from_code(code) else {
return Ok(());
};
if let Some(win) = self.win.as_mut() {
win.screen.key(key, pressed);
}
Ok(())
}
/// `WinScreen.tick`: done once everything has rolled past the top.
pub(super) fn tick_win_screen(&mut self) -> Result<()> {
let height = self.gui_size().1;
if self.win.as_ref().is_some_and(|w| w.screen.finished(height)) {
self.close_win_screen()?;
}
Ok(())
}
/// `WinScreen.respawn` (`onFinished`) and `removed`: the credits music stops.
pub(super) fn close_win_screen(&mut self) -> Result<()> {
let Some(win) = self.win.take() else {
return Ok(());
};
let credits = horizon_client::music::Music::credits();
self.music
.stop_playing_music(&credits, None, &mut self.audio);
match win.finish {
Finish::Options => self.screen = Screen::Options,
Finish::Closed if self.title.is_some() => self.screen = Screen::Playing,
Finish::Respawn | Finish::RemoteRespawn | Finish::Closed => {
if win.finish == Finish::RemoteRespawn {
self.remote_respawn();
}
self.screen = Screen::Playing;
self.capture(true);
}
}
Ok(())
}
}
+99 -10
View File
@@ -395,6 +395,8 @@ pub struct HudBatch {
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges with another blend or depth/scissor state, in order.
pub blends: Vec<(std::ops::Range<u32>, Blend)>,
/// The textures and time of the `Blend::EndPortal` runs.
pub end_portal: EndPortalFill,
/// Screen's first vertex: the preceding HUD is part of its blurred background.
pub blur_at: u32,
}
@@ -409,6 +411,19 @@ pub enum Blend {
Additive,
/// Alpha blending with an isolated depth buffer and a pixel scissor.
Depth([u32; 4]),
/// `RenderPipelines.VIGNETTE`: the destination darkened by the texture
/// (`ZERO, ONE_MINUS_SRC_COLOR`).
Vignette,
/// `RenderPipelines.END_PORTAL` as a GUI fill: the End portal's layers
/// projected from the screen (`HudBatch::end_portal` sets the textures).
EndPortal,
}
/// What a `Blend::EndPortal` fill samples: the atlas rects (u0, v0, width,
/// height) of `end_sky.png` and `end_portal.png`, and the `GameTime` uniform.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct EndPortalFill {
pub sprites: [[f32; 4]; 2],
pub game_time: f32,
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
@@ -432,6 +447,7 @@ impl HudBatch {
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
blends: Vec::new(),
end_portal: EndPortalFill::default(),
blur_at: 0,
}
}
@@ -738,7 +754,13 @@ impl HudBatch {
let mut glyphs = Vec::new();
let mut cursor = x;
for (i, (ch, style)) in text.chars().enumerate() {
let g = font.glyph(ch);
// The style's font (`Style.getFont`), the default one unless set.
let mut g = font.glyph_styled(ch, style);
// Font.StringRenderOutput.accept: obfuscated characters draw a
// random glyph of the same width each frame.
if style.obfuscated == Some(true) && ch != ' ' {
g = font.random_glyph(style, g.advance);
}
let c = style.color.map_or(color, |rgb| {
rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha)
});
@@ -832,6 +854,20 @@ impl HudBatch {
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct HudUniform {
size: [f32; 4],
/// `EndPortalFill`: the two sprites, then the game time in x.
end_portal: [[f32; 4]; 3],
}
impl HudUniform {
fn new(size: [f32; 4], fill: EndPortalFill) -> Self {
Self {
size,
end_portal: [
fill.sprites[0],
fill.sprites[1],
[fill.game_time, 0.0, 0.0, 0.0],
],
}
}
}
pub struct HudRenderer {
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>,
@@ -842,6 +878,8 @@ pub struct HudRenderer {
invert_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
depth_pipeline: wgpu::RenderPipeline,
vignette_pipeline: wgpu::RenderPipeline,
end_portal_pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
@@ -864,7 +902,7 @@ impl HudRenderer {
});
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("HUD size"),
contents: bytemuck::bytes_of(&HudUniform { size: [1.0; 4] }),
contents: bytemuck::bytes_of(&HudUniform::new([1.0; 4], EndPortalFill::default())),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -872,7 +910,7 @@ impl HudRenderer {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
@@ -1000,6 +1038,31 @@ impl HudRenderer {
"fs_main",
false,
);
// RenderPipelines.VIGNETTE: ZERO, ONE_MINUS_SRC_COLOR, ZERO, ONE.
let vignette_pipeline = create(
"HUD vignette",
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
},
"fs_main",
false,
);
// RenderPipelines.END_PORTAL: opaque.
let end_portal_pipeline = create(
"HUD end portal",
wgpu::BlendState::REPLACE,
"fs_end_portal",
false,
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
@@ -1014,6 +1077,8 @@ impl HudRenderer {
invert_pipeline,
additive_pipeline,
depth_pipeline,
vignette_pipeline,
end_portal_pipeline,
group,
uniform,
buffer,
@@ -1107,9 +1172,10 @@ impl HudRenderer {
encoder,
&self.uniform,
0,
bytemuck::bytes_of(&HudUniform {
size: [size[0] as f32, size[1] as f32, batch.scale, 0.0],
}),
bytemuck::bytes_of(&HudUniform::new(
[size[0] as f32, size[1] as f32, batch.scale, 0.0],
batch.end_portal,
)),
);
}
/// Draw the batch `prepare` staged.
@@ -1197,6 +1263,8 @@ impl HudRenderer {
Blend::Invert => &self.invert_pipeline,
Blend::Additive => &self.additive_pipeline,
Blend::Depth(_) => &self.depth_pipeline,
Blend::Vignette => &self.vignette_pipeline,
Blend::EndPortal => &self.end_portal_pipeline,
});
pass.draw(range.clone(), 0..1);
}
@@ -1209,10 +1277,10 @@ impl HudRenderer {
mod tests {
use super::*;
#[test]
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
let root = std::env::temp_dir().join(format!("horizon-fonts-atlas-{}", std::process::id()));
/// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
fn two_glyph_font(name: &str) -> std::path::PathBuf {
let root =
std::env::temp_dir().join(format!("horizon-fonts-{name}-{}", std::process::id()));
let font = root.join("assets/minecraft/font");
let textures = root.join("assets/minecraft/textures/font");
fs::create_dir_all(&font).unwrap();
@@ -1237,6 +1305,11 @@ mod tests {
.unwrap()
.write_image_data(&pixels)
.unwrap();
root
}
#[test]
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
let root = two_glyph_font("atlas");
let full = HudAtlas::build(&root).unwrap();
let fonts = HudAtlas::fonts(&root).unwrap();
let _ = fs::remove_dir_all(&root);
@@ -1245,6 +1318,21 @@ mod tests {
assert!(width > 0.0);
assert_eq!(fonts.font.width("abba"), width);
}
#[test]
fn obfuscated_glyphs_keep_the_width() {
let root = two_glyph_font("obfuscated");
let fonts = HudAtlas::fonts(&root).unwrap();
let _ = fs::remove_dir_all(&root);
let (a, b) = (fonts.font.glyph('a').advance, fonts.font.glyph('b').advance);
assert_ne!(a, b);
for _ in 0..20 {
assert_eq!(fonts.font.random_glyph(&Default::default(), a).advance, a);
assert_eq!(fonts.font.random_glyph(&Default::default(), b).advance, b);
}
// No glyph that wide: FontSet's missing glyph.
let missing = fonts.font.random_glyph(&Default::default(), 30.0);
assert!(missing.rect.is_none() && missing.right == 5.0);
}
#[test]
fn effect_icons_are_painted_from_the_mob_effect_directory() {
@@ -1429,6 +1517,7 @@ mod tests {
height: height as f32,
patches: Vec::new(),
blends: Vec::new(),
end_portal: EndPortalFill::default(),
blur_at: 0,
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
+50 -1
View File
@@ -1,4 +1,9 @@
struct Hud { size: vec4<f32> }
struct Hud {
size: vec4<f32>,
// Blend::EndPortal: atlas rects (u0, v0, width, height) of end_sky.png and
// end_portal.png, then vanilla's GameTime in x.
end_portal: array<vec4<f32>, 3>,
}
@group(0) @binding(0) var<uniform> hud: Hud;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;
@@ -6,6 +11,8 @@ struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
// projection_from_position(gl_Position): the End portal's texProj0.
@location(2) proj: vec4<f32>,
}
@vertex fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>, @location(3) depth: f32) -> Out {
let pixels = pos * hud.size.z;
@@ -13,6 +20,7 @@ struct Out {
out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, depth, 1.0);
out.uv = uv;
out.color = color;
out.proj = vec4(out.clip.xy * 0.5 + 0.5, out.clip.zw);
return out;
}
@fragment fn fs_main(in: Out) -> @location(0) vec4<f32> {
@@ -31,3 +39,44 @@ struct Out {
if c.a == 0.0 { discard; }
return c;
}
// rendertype_end_portal.fsh (entity.wgsl has the same for portal blocks).
const PORTAL_COLORS = array<vec3<f32>, 16>(
vec3(0.022087, 0.098399, 0.110818),
vec3(0.011892, 0.095924, 0.089485),
vec3(0.027636, 0.101689, 0.100326),
vec3(0.046564, 0.109883, 0.114838),
vec3(0.064901, 0.117696, 0.097189),
vec3(0.063761, 0.086895, 0.123646),
vec3(0.084817, 0.111994, 0.166380),
vec3(0.097489, 0.154120, 0.091064),
vec3(0.106152, 0.131144, 0.195191),
vec3(0.097721, 0.110188, 0.187229),
vec3(0.133516, 0.138278, 0.148582),
vec3(0.070006, 0.243332, 0.235792),
vec3(0.196766, 0.142899, 0.214696),
vec3(0.047281, 0.315338, 0.321970),
vec3(0.204675, 0.390010, 0.302066),
vec3(0.080955, 0.314821, 0.661491),
);
fn portal_sample(rect: vec4<f32>, p: vec4<f32>) -> vec3<f32> {
let st = fract(p.xy / p.w);
return textureSampleLevel(atlas, atlas_sampler, rect.xy + st * rect.zw, 0.0).rgb;
}
fn portal_layer(p: vec4<f32>, layer: f32) -> vec4<f32> {
let a = radians((layer * layer * 4321.0 + layer * 9.0) * 2.0);
let c = cos(a);
let s = sin(a);
let k = (4.5 - layer / 4.0) * 2.0;
var v = vec4(k * (c * p.x - s * p.y), k * (s * p.x + c * p.y), p.z, p.w);
v = vec4(v.x + 17.0 / layer * v.w, v.y + (2.0 + layer / 1.5) * (hud.end_portal[2].x * 1.5) * v.w, v.z, v.w);
return vec4(0.5 * v.x + 0.25 * v.w, 0.5 * v.y + 0.25 * v.w, v.z, v.w);
}
// RenderPipelines.END_PORTAL (WinScreen's poem background): end_sky and 15
// layers of end_portal.png.
@fragment fn fs_end_portal(in: Out) -> @location(0) vec4<f32> {
var c = portal_sample(hud.end_portal[0], in.proj) * PORTAL_COLORS[0];
for (var i = 0; i < 15; i++) {
c += portal_sample(hud.end_portal[1], portal_layer(in.proj, f32(i + 1))) * PORTAL_COLORS[i];
}
return vec4(c, 1.0);
}
+5
View File
@@ -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])>,
@@ -259,6 +263,7 @@ impl Guest {
sleep_timer: 0,
sent_bed: None,
spawn: None,
respawn_elsewhere: None,
awaiting_teleport: None,
teleport_counter: 0,
teleport_tick: 0,
+18 -3
View File
@@ -842,6 +842,20 @@ impl Hub {
/// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation.
pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) {
self.teleport_relative(i, position, 0);
}
/// A teleport to `position` that keeps the player's motion and look
/// (`Relative.DELTA` and `Relative.ROTATION`: an End gateway's).
pub fn teleport_keeping_motion(&mut self, i: usize, position: [f64; 3]) {
use play::relative::{DELTA_X, DELTA_Y, DELTA_Z, ROTATE_DELTA, X_ROT, Y_ROT};
let relatives = Y_ROT | X_ROT | DELTA_X | DELTA_Y | DELTA_Z | ROTATE_DELTA;
self.teleport_relative(i, Some(position), relatives);
}
/// ServerGamePacketListenerImpl.teleport with `relatives`: the rotation
/// and motion they name are sent as zero changes.
fn teleport_relative(&mut self, i: usize, position: Option<[f64; 3]>, relatives: i32) {
let ticks = self.ticks;
let g = &mut self.guests[i];
g.teleport_tick = ticks;
@@ -852,13 +866,14 @@ impl Hub {
g.teleport_counter = (g.teleport_counter + 1) & 0x7FFF_FFFF;
let id = g.teleport_counter;
g.awaiting_teleport = Some((id, g.position));
let turn = relatives & (play::relative::Y_ROT | play::relative::X_ROT) != 0;
g.send(&C::PlayerPosition(play::PlayerPosition {
teleport: id,
position: g.position,
delta: [0.0; 3],
yaw: g.yaw,
pitch: g.pitch,
relatives: 0,
yaw: if turn { 0.0 } else { g.yaw },
pitch: if turn { 0.0 } else { g.pitch },
relatives,
}));
}
@@ -73,6 +73,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() {
@@ -142,6 +143,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();
+1
View File
@@ -188,6 +188,7 @@ pub mod vanillagen;
pub mod vault;
pub mod weather;
pub mod widgets;
pub mod win_screen;
pub mod window;
pub mod world;
pub mod world_spawn;
+58 -3
View File
@@ -871,6 +871,8 @@ pub enum Page {
Controller,
PadBinds,
Extras,
/// CreditsAndAttributionScreen.
Credits,
/// Horizon Settings: every page Horizon adds, as a mod's settings
/// screen hangs off vanilla's Options.
Horizon,
@@ -896,6 +898,8 @@ enum Act {
/// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off).
ToggleShaderPack(usize),
OpenShaderPackFolder,
/// Credits & Attribution's Credits button (WinScreen without the poem).
Credits,
CopyAgentDetails,
}
enum WKind {
@@ -946,6 +950,8 @@ pub enum Event {
OpenModFolder,
/// Create `shaderpacks/` if needed and open it.
OpenShaderPackFolder,
/// Roll the credits (`CreditsAndAttributionScreen.openCreditsScreen`).
Credits,
/// Copy how an agent connects (the AI Agent page).
CopyAgentDetails,
}
@@ -1213,6 +1219,7 @@ impl OptionsUi {
Page::Controller => "Controller Settings",
Page::PadBinds => "Controller Binds",
Page::Extras => "Horizon Extras",
Page::Credits => "credits_and_attribution.screen.title",
Page::Horizon => "Horizon Settings",
Page::Agent => "AI Agent",
}
@@ -1633,10 +1640,13 @@ impl OptionsUi {
("options.accessibility", Some(Page::Accessibility)),
// Vanilla's Telemetry Data and Credits slots: Horizon's
// settings and its mods, as a mod adds its button here.
// Credits & Attribution (WinScreen's credits) follows them.
("Horizon Settings...", Some(Page::Horizon)),
("Mods...", Some(Page::Mods)),
("options.credits_and_attribution", Some(Page::Credits)),
];
let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0);
let rows = entries.len().div_ceil(2) as f32;
let gy = (61.0 + 30.0f32).min(h - 33.0 - rows * 24.0);
for (i, (key, page)) in entries.iter().enumerate() {
let x = cx - 158.0 + 4.0 + (i % 2) as f32 * 158.0;
let y = gy + (i / 2) as f32 * 24.0;
@@ -1647,6 +1657,46 @@ impl OptionsUi {
top = 0.0;
bottom = 0.0;
}
Page::Credits => {
// CreditsAndAttributionScreen: the title header, three 210-wide
// buttons 8 apart (HeaderAndFooterLayout: 30 below the header
// unless the footer is closer), Done.
out.push(Widget {
x: 0.0,
y: 12.0,
w,
h: 9.0,
kind: WKind::Text {
text: tr(Self::title(page)),
color: u32::MAX,
centered: true,
},
list: false,
});
let y = (33.0 + 30.0f32).min(h - 33.0 - 76.0);
let x = cx - 105.0;
out.push(button(
x,
y,
210.0,
tr("credits_and_attribution.button.credits"),
Act::Credits,
));
// ConfirmLinkScreen to minecraft.net: Horizon opens no links.
for (i, key) in [
"credits_and_attribution.button.attribution",
"credits_and_attribution.button.licenses",
]
.into_iter()
.enumerate()
{
let y = y + 28.0 * (i + 1) as f32;
out.push(inactive(button(x, y, 210.0, tr(key), Act::None)));
}
out.push(done(h - 27.0));
top = 0.0;
bottom = 0.0;
}
Page::KeyBinds => {
top = 38.0;
out.push(Widget {
@@ -2537,6 +2587,7 @@ impl OptionsUi {
events.push(Event::Changed);
}
Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder),
Act::Credits => events.push(Event::Credits),
Act::CopyAgentDetails => events.push(Event::CopyAgentDetails),
Act::None => {}
}
@@ -4172,9 +4223,13 @@ mod tests {
})
.collect()
};
// Vanilla's ten Options buttons, the last two Horizon's.
// Vanilla's Options buttons, Horizon's two in the Telemetry and Credits slots, then
// Credits & Attribution (WinScreen's credits).
let main = pushes(&mut ui);
assert_eq!(&main[main.len() - 2..], [Page::Horizon, Page::Mods]);
assert_eq!(
&main[main.len() - 3..],
[Page::Horizon, Page::Mods, Page::Credits]
);
ui.push(Page::Horizon);
assert_eq!(
pushes(&mut ui),
+1
View File
@@ -87,6 +87,7 @@ fn style_of(o: &serde_json::Map<String, serde_json::Value>) -> Style {
underlined: flag("underlined"),
strikethrough: flag("strikethrough"),
obfuscated: flag("obfuscated"),
font: o.get("font").and_then(crate::text::font_id),
..Style::default()
}
}
+4
View File
@@ -2276,6 +2276,8 @@ pub struct Level {
pub inventory_components: HashMap<u8, Box<crate::item_data::StackData>>,
/// Player.XpSeed: the enchanting table seed.
pub xp_seed: i32,
/// ServerPlayer.seenCredits: the end poem has been shown.
pub seen_credits: bool,
/// Player.active_effects: (id, duration, amplifier, ambient, show_icon).
pub active_effects: Vec<(String, i32, i32, bool, bool)>,
/// Player.EnderItems: the ender chest inventory (27 slots).
@@ -2468,6 +2470,7 @@ impl Level {
self.selected_slot = n("SelectedItemSlot").unwrap_or(0) as i32;
self.fall_distance = f("fall_distance").unwrap_or(0.0);
self.on_ground = n("OnGround").unwrap_or(0) != 0;
self.seen_credits = n("seenCredits").unwrap_or(0) != 0;
if let Some(mode) = n("playerGameType") {
self.creative = mode == 1;
self.game_mode = mode as i32;
@@ -2690,6 +2693,7 @@ impl Level {
if let Some(pos) = self.position {
entries.push(("Pos", doubles(&pos)));
}
entries.push(("seenCredits", Tag::Byte(i8::from(self.seen_credits))));
// A respawn point other than the world spawn: an anchor elsewhere, or a bed.
if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere {
let mut respawn = vec![
+1
View File
@@ -118,6 +118,7 @@ pub fn style_from_json(v: &Value) -> Style {
s.underlined = flag("underlined");
s.strikethrough = flag("strikethrough");
s.obfuscated = flag("obfuscated");
s.font = o.get("font").and_then(text::font_id);
s
}
impl NumberFormat {
+15 -1
View File
@@ -61,6 +61,13 @@ pub struct Style {
pub click: Option<ClickEvent>,
/// Hover text.
pub hover: Option<Box<Text>>,
/// The font (`FontDescription.Resource`), a full id like
/// `minecraft:alt`; the default font when unset.
pub font: Option<String>,
}
/// A style's `font` field: an identifier (`alt` is `minecraft:alt`).
pub fn font_id(v: &Value) -> Option<String> {
crate::command::args::parse_identifier(v.as_str()?)
}
impl Style {
pub fn color(c: u32) -> Self {
@@ -83,6 +90,9 @@ impl Style {
if self.hover.is_none() {
self.hover.clone_from(&base.hover);
}
if self.font.is_none() {
self.font.clone_from(&base.font);
}
}
pub fn is_bold(&self) -> bool {
self.bold == Some(true)
@@ -451,7 +461,7 @@ impl Text {
}
/// The style fields of a component's JSON.
const STYLE_KEYS: [&str; 8] = [
const STYLE_KEYS: [&str; 9] = [
"color",
"bold",
"italic",
@@ -460,6 +470,7 @@ const STYLE_KEYS: [&str; 8] = [
"obfuscated",
"click_event",
"hover_event",
"font",
];
/// Style.Serializer: the fields a style sets.
fn style_json(style: &Style) -> Vec<(String, Value)> {
@@ -500,6 +511,9 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
json!({ "action": "show_text", "value": hover.component() }),
));
}
if let Some(font) = &style.font {
out.push(("font".to_owned(), font.clone().into()));
}
out
}
+452
View File
@@ -0,0 +1,452 @@
//! `WinScreen`: the end poem, the credits and the post-credits text rolling up
//! under the logo, after the player leaves the End for the first time (with
//! the poem) or from Credits & Attribution (the credits alone). The texts come
//! from the resource root, so resource packs can replace them.
use crate::{
font::Font,
hud::{Blend, EndPortalFill, HudAtlas, HudBatch},
text::{self, Style, Text},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::{collections::HashSet, path::Path};
/// `WinScreen.OBFUSCATE_TOKEN`: `§f§k§a§b` marks where the poem hides a name.
const OBFUSCATE_TOKEN: &str = "\u{a7}f\u{a7}k\u{a7}a\u{a7}b";
/// `WinScreen.NAME_PREFIX`.
const NAME_PREFIX: &str = " ";
/// `WinScreen.SECTION_HEADING`.
const SECTION_HEADING: &str = "============";
/// A key the screen reacts to (`keyPressed` / `keyReleased`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
/// `KeyEvent.isUp`: the up arrow scrolls back.
Up,
/// Space speeds the scroll up.
Space,
/// Each held Control key speeds it up more.
LeftControl,
RightControl,
}
impl Key {
pub fn from_code(code: winit::keyboard::KeyCode) -> Option<Self> {
use winit::keyboard::KeyCode;
match code {
KeyCode::ArrowUp => Some(Self::Up),
KeyCode::Space => Some(Self::Space),
KeyCode::ControlLeft => Some(Self::LeftControl),
KeyCode::ControlRight => Some(Self::RightControl),
_ => None,
}
}
}
pub struct WinScreen {
pub poem: bool,
lines: Vec<Text>,
centered: HashSet<usize>,
total_scroll_length: i32,
scroll: f32,
speedup_active: bool,
speedup_modifiers: HashSet<Key>,
unmodified_scroll_speed: f32,
scroll_speed: f32,
direction: i32,
}
impl WinScreen {
/// `WinScreen.<init>` and `init`: the poem (`texts/end.txt`) when `poem`,
/// the credits (`texts/credits.json`), then `texts/postcredits.txt`.
pub fn new(poem: bool, root: &Path, player: &str, font: &Font) -> Self {
let speed = if poem { 0.5 } else { 0.75 };
let mut screen = Self {
poem,
lines: Vec::new(),
centered: HashSet::new(),
total_scroll_length: 0,
scroll: 0.0,
speedup_active: false,
speedup_modifiers: HashSet::new(),
unmodified_scroll_speed: speed,
scroll_speed: speed,
direction: 1,
};
let texts = root.join("assets/minecraft/texts");
let read = |name: &str| match std::fs::read_to_string(texts.join(name)) {
Ok(s) => Some(s),
Err(e) => {
log::error!("Couldn't load credits from file minecraft:texts/{name}: {e}");
None
}
};
if poem && let Some(s) = read("end.txt") {
screen.add_poem_file(&s, player, font);
}
if let Some(s) = read("credits.json") {
match serde_json::from_str(&s) {
Ok(json) => screen.add_credits_file(&json),
Err(e) => {
log::error!("Couldn't load credits from file minecraft:texts/credits.json: {e}")
}
}
}
if poem && let Some(s) = read("postcredits.txt") {
screen.add_poem_file(&s, player, font);
}
screen.total_scroll_length = screen.lines.len() as i32 * 12;
screen
}
/// `addPoemFile`: each line with the player's name in, its obfuscated
/// spans turned into 3 to 6 scrambled characters, wrapped at 256 pixels
/// and followed by an empty line; 8 more empty lines at the end.
fn add_poem_file(&mut self, file: &str, player: &str, font: &Font) {
let mut random = LegacyRandom::new(8124371);
// BufferedReader.readLine: \n, \r or \r\n end a line; no empty last line.
let mut lines: Vec<&str> = file
.split('\n')
.map(|l| l.strip_suffix('\r').unwrap_or(l))
.collect();
if file.ends_with('\n') {
lines.pop();
}
for line in lines.iter().flat_map(|l| l.split('\r')) {
let mut line = line.replace("PLAYERNAME", player);
while let Some(pos) = line.find(OBFUSCATE_TOKEN) {
let n = random.next_int_bound(4).unwrap_or(0) as usize + 3;
line = format!(
"{}\u{a7}f\u{a7}k{}{}",
&line[..pos],
&"XXXXXXXX"[..n],
&line[pos + OBFUSCATE_TOKEN.len()..]
);
}
let text = Text::legacy(&line);
self.lines
.extend(font.split_lines(&text, 256.0).into_iter().map(|(t, _)| t));
self.add_empty_line();
}
for _ in 0..8 {
self.add_empty_line();
}
}
/// `addCreditsFile`: each section's heading, then each discipline's name
/// and its titles with the names under them.
fn add_credits_file(&mut self, json: &serde_json::Value) {
let colored = |s: &str, color: u32| Text::styled(s, Style::color(color));
let heading = || colored(SECTION_HEADING, text::WHITE);
for section in json.as_array().into_iter().flatten() {
let name = section["section"].as_str().unwrap_or_default();
self.add_credits_line(heading(), true);
self.add_credits_line(colored(name, text::YELLOW), true);
self.add_credits_line(heading(), true);
self.add_empty_line();
self.add_empty_line();
for discipline in section["disciplines"].as_array().into_iter().flatten() {
let name = discipline["discipline"].as_str().unwrap_or_default();
if !name.is_empty() {
self.add_credits_line(colored(name, text::YELLOW), true);
self.add_empty_line();
self.add_empty_line();
}
for title in discipline["titles"].as_array().into_iter().flatten() {
let name = title["title"].as_str().unwrap_or_default();
self.add_credits_line(colored(name, text::GRAY), false);
for name in title["names"].as_array().into_iter().flatten() {
let line = format!("{NAME_PREFIX}{}", name.as_str().unwrap_or_default());
self.add_credits_line(colored(&line, text::WHITE), false);
}
self.add_empty_line();
self.add_empty_line();
}
}
}
}
fn add_empty_line(&mut self) {
self.lines.push(Text::empty());
}
fn add_credits_line(&mut self, line: Text, centered: bool) {
if centered {
self.centered.insert(self.lines.len());
}
self.lines.push(line);
}
/// The lines in order and whether each is centred.
pub fn lines(&self) -> impl Iterator<Item = (&Text, bool)> {
self.lines
.iter()
.enumerate()
.map(|(i, l)| (l, self.centered.contains(&i)))
}
fn calculate_scroll_speed(&self) -> f32 {
let speed = if self.speedup_active {
self.unmodified_scroll_speed * (5.0 + self.speedup_modifiers.len() as f32 * 15.0)
} else {
self.unmodified_scroll_speed
};
speed * self.direction as f32
}
/// `keyPressed` / `keyReleased` (Escape closes the screen: `onClose`).
pub fn key(&mut self, key: Key, pressed: bool) {
match (key, pressed) {
(Key::Up, _) => self.direction = if pressed { -1 } else { 1 },
(Key::Space, _) => self.speedup_active = pressed,
(_, true) => {
self.speedup_modifiers.insert(key);
}
(_, false) => {
self.speedup_modifiers.remove(&key);
}
}
self.scroll_speed = self.calculate_scroll_speed();
}
/// `tick`: once the text has rolled past the top, the screen is done
/// (`respawn`, or back to the screen that opened it).
pub fn finished(&self, height: f32) -> bool {
let height = height as i32;
self.scroll > (self.total_scroll_length + height + height + 24) as f32
}
pub fn scroll(&self) -> f32 {
self.scroll
}
/// Stay `scroll` pixels in (until a key changes the speed), for
/// screenshots.
pub fn hold(&mut self, scroll: f32) {
self.scroll = scroll;
self.scroll_speed = 0.0;
}
/// `extractRenderState` after a frame of `delta_ticks` game ticks:
/// `extractBackground`, the vignette, then the logo and the lines
/// scrolled up. The poem's End portal background samples `end_portal`;
/// the credits draw the scrolling menu background (over the blurred
/// panorama on the title screen).
pub fn draw(
&mut self,
batch: &mut HudBatch,
atlas: &HudAtlas,
delta_ticks: f32,
end_portal: EndPortalFill,
) {
let (w, h) = (batch.width, batch.height);
if self.poem {
let start = batch.vertices.len();
batch.fill(atlas, 0.0, 0.0, w, h, u32::MAX);
batch.blend_since(start, Blend::EndPortal);
batch.end_portal = end_portal;
} else {
self.menu_background(batch, atlas, w, h);
}
// extractVignette: credits_vignette.png stretched over the screen.
if let Some(r) = atlas.sprites.get("misc/credits_vignette").copied() {
let start = batch.vertices.len();
batch.rect_uv(0.0, 0.0, w, h, r, u32::MAX);
batch.blend_since(start, Blend::Vignette);
}
self.scroll = (self.scroll + delta_ticks * self.scroll_speed).max(0.0);
let logo_x = (w / 2.0).floor() - 128.0;
let logo_y = h + 50.0;
// Everything below is drawn translated by `y_offs`.
let y_offs = -self.scroll;
// LogoRenderer(false) at full alpha.
let edition_x = (w / 2.0).floor() - 64.0;
batch.sprite_region(
atlas,
"gui/title/minecraft",
[logo_x, logo_y + y_offs, 256.0, 44.0],
256.0,
64.0,
);
batch.sprite_region(
atlas,
crate::title_edition::SPRITE,
[edition_x, logo_y + 44.0 - 7.0 + y_offs, 128.0, 14.0],
128.0,
16.0,
);
let mut y_pos = logo_y + 100.0;
let last = self.lines.len().saturating_sub(1);
for (i, line) in self.lines.iter().enumerate() {
let mut shift = y_offs;
if i == last {
// The last line stops in the middle of the screen.
let diff = y_pos + y_offs - ((h as i32 / 2) as f32 - 6.0);
if diff < 0.0 {
shift -= diff;
}
}
if y_pos + y_offs + 12.0 + 8.0 > 0.0 && y_pos + y_offs < h {
let x = if self.centered.contains(&i) {
// GuiGraphicsExtractor.centeredText: x - width / 2.
logo_x + 128.0 - (atlas.font.width_text(line) as i32 / 2) as f32
} else {
logo_x
};
batch.text_styled(atlas, line, x, y_pos + shift, u32::MAX, true);
}
y_pos += 12.0;
}
}
/// `extractMenuBackground`: `menu_background.png` tiled at 32 pixels,
/// scrolled by half the text's scroll.
fn menu_background(&self, batch: &mut HudBatch, atlas: &HudAtlas, w: f32, h: f32) {
let v = (self.scroll * 0.5).rem_euclid(32.0);
let start = batch.vertices.len();
crate::ui::tiled(
batch,
atlas,
"gui/menu_background",
0.0,
-v,
w,
h + 32.0,
32.0,
u32::MAX,
);
batch.clip_since(start, 0.0, 0.0, w, h);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A resource root with only the credits texts: every glyph is the
/// missing one, 6 pixels wide.
fn screen(poem: bool, end: &str, credits: &str, post: &str) -> WinScreen {
let root = std::env::temp_dir().join(format!(
"horizon-win-screen-{}-{poem}-{}",
std::process::id(),
end.len()
));
let texts = root.join("assets/minecraft/texts");
std::fs::create_dir_all(&texts).unwrap();
std::fs::write(texts.join("end.txt"), end).unwrap();
std::fs::write(texts.join("credits.json"), credits).unwrap();
std::fs::write(texts.join("postcredits.txt"), post).unwrap();
let atlas = HudAtlas::fonts(&root).unwrap();
let screen = WinScreen::new(poem, &root, "Steve", &atlas.font);
let _ = std::fs::remove_dir_all(&root);
screen
}
const CREDITS: &str = r#"[{"section":"Studio","disciplines":[
{"discipline":"","titles":[{"title":"Head","names":["Ada","Bo"]}]},
{"discipline":"Art","titles":[{"title":"Artist","names":[]}]}]}]"#;
#[test]
fn the_poem_names_the_player_and_scrambles_its_hidden_names() {
let s = screen(
true,
"\u{a7}3Hello PLAYERNAME.\r\n\n\u{a7}2\u{a7}f\u{a7}k\u{a7}a\u{a7}bkey\n",
"[]",
"End.",
);
let lines: Vec<(String, bool)> = s.lines().map(|(t, c)| (t.plain(), c)).collect();
// Each line then an empty one; the empty line adds no text line; 8
// empty lines after each file.
let mut want = vec!["Hello Steve.", ""];
want.push("");
// LegacyRandom(8124371).nextInt(4) + 3 scrambled characters.
let n = LegacyRandom::new(8124371).next_int_bound(4).unwrap() as usize + 3;
let hidden = format!("{}key", &"XXXXXXXX"[..n]);
want.extend([hidden.as_str(), ""]);
want.extend([""; 8]);
want.extend(["End.", ""]);
want.extend([""; 8]);
assert_eq!(
lines,
want.iter()
.map(|l| (l.to_string(), false))
.collect::<Vec<_>>()
);
let hidden_line = s.lines().nth(3).unwrap().0;
let styles: Vec<_> = hidden_line.chars().map(|(_, s)| s.obfuscated).collect();
assert!(styles[..n].iter().all(|o| *o == Some(true)));
assert_eq!(s.total_scroll_length, lines.len() as i32 * 12);
}
#[test]
fn long_poem_lines_wrap_at_256_pixels() {
// 6-pixel glyphs: 42 fit a line, and the space at each break goes.
let line = vec!["a"; 50].join(" ");
let s = screen(true, &line, "[]", "");
let lines: Vec<String> = s.lines().take(4).map(|(t, _)| t.plain()).collect();
assert_eq!(
lines.iter().map(|l| l.chars().count()).collect::<Vec<_>>(),
[41, 41, 15, 0]
);
assert!(lines.iter().all(|l| !l.starts_with(' ')));
}
#[test]
fn credits_centre_the_headings_and_list_the_names() {
let s = screen(false, "ignored", CREDITS, "ignored");
let lines: Vec<(String, bool)> = s.lines().map(|(t, c)| (t.plain(), c)).collect();
let l = |s: &str, c| (s.to_string(), c);
let names = |n: &str| l(&format!("{NAME_PREFIX}{n}"), false);
assert_eq!(
lines,
vec![
l(SECTION_HEADING, true),
l("Studio", true),
l(SECTION_HEADING, true),
l("", false),
l("", false),
l("Head", false),
names("Ada"),
names("Bo"),
l("", false),
l("", false),
l("Art", true),
l("", false),
l("", false),
l("Artist", false),
l("", false),
l("", false),
]
);
let color = |i: usize| s.lines().nth(i).unwrap().0.chars().next().unwrap().1.color;
assert_eq!(
[color(0), color(1), color(5), color(6), color(10)],
[
Some(text::WHITE),
Some(text::YELLOW),
Some(text::GRAY),
Some(text::WHITE),
Some(text::YELLOW)
]
);
}
#[test]
fn keys_set_the_scroll_speed_and_direction() {
let mut s = screen(false, "", CREDITS, "");
assert_eq!(s.scroll_speed, 0.75);
s.key(Key::Space, true);
assert_eq!(s.scroll_speed, 0.75 * 5.0);
s.key(Key::LeftControl, true);
s.key(Key::RightControl, true);
assert_eq!(s.scroll_speed, 0.75 * 35.0);
s.key(Key::Up, true);
assert_eq!(s.scroll_speed, -0.75 * 35.0);
s.key(Key::Space, false);
assert_eq!(s.scroll_speed, -0.75);
s.key(Key::Up, false);
s.key(Key::LeftControl, false);
assert_eq!(s.scroll_speed, 0.75);
// The poem rolls at 0.5 pixels a tick.
assert_eq!(screen(true, "", CREDITS, "").scroll_speed, 0.5);
}
#[test]
fn the_screen_ends_once_everything_rolled_past() {
let mut s = screen(false, "", CREDITS, "");
let atlas = HudAtlas::fonts(Path::new("/nonexistent")).unwrap();
let mut batch = HudBatch::new([640, 480]);
let h = batch.height;
let end = (s.total_scroll_length as f32 + 2.0 * h + 24.0) / 0.75;
s.draw(&mut batch, &atlas, end - 1.0, EndPortalFill::default());
assert!(!s.finished(h));
// Scrolling back never goes above the start.
s.key(Key::Up, true);
s.draw(&mut batch, &atlas, end * 2.0, EndPortalFill::default());
assert_eq!(s.scroll(), 0.0);
s.key(Key::Up, false);
s.draw(&mut batch, &atlas, end + 1.0, EndPortalFill::default());
assert!(s.finished(h));
}
}
+93
View File
@@ -0,0 +1,93 @@
# A server's levels: one per dimension
Vanilla's `MinecraftServer` holds a `ServerLevel` per dimension, and each player is in one of them.
Horizon's server does the same. That covers the dedicated server and single player's server thread
(`Game::serving`, the default since #1114). So a LAN world's host and each guest can be in different
dimensions at the same time.
## How the single-level `Game` maps onto vanilla's levels
The game's tick code reads one level: the one held in `Game`'s own fields (the world, its streaming
and save, block ticks, entities, block entities and their per-level queues). `game/levels.rs` keeps
the other dimensions' levels as `Parked` values and swaps one into place (`enter_level`). The swap is
`mem::swap` of each per-level field, so the tick code runs unchanged, one level at a time.
| Vanilla | Horizon |
| --- | --- |
| `MinecraftServer.levels` | the level in place plus `Levels::parked` |
| `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`: 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) |
The packets of a guest are read in its own level's pass (`Hub::tick_level`), so its actions and
commands run with its level in place.
The window's own game (`--no-server-thread`, `HORIZON_SERVER_THREAD=0`, and the command harness) keeps
one level, which follows its player (`enter_dimension`). LAN guests of a world run that way stay in the
host's dimension. That mode is the escape hatch now, so it gets no multi-level work.
## One code path for both
The dedicated server and the server thread are the same code. The server thread runs a `Game` with
`options.dedicated` set and a hub without a host player. The window joins it through memory as one
more player. Everything above serves both, and `server_dimension_players` (vanilla clients on Horizon's
dedicated server) and `lan_e2e --server-thread` (Horizon clients on the server thread) check it from
the two sides.
## Cost of an extra level
Measured on the Mac mini (M4 Pro) at render distance 12, on 2026-10-22. The host and a guest each
played a fresh world on the server thread. RSS is the host's whole process, window included. Tick time
is `/tick query`'s average over 100 ticks.
| Where the players are | Average tick | P95 | Host RSS |
| --- | --- | --- | --- |
| both in the Overworld | 1.0 ms | 1.3 ms | 1194 MB |
| guest in the Nether (two levels tick) | 2.2 ms | 2.9 ms | 1238 MB |
| guest in the End (the Nether still parked) | 0.9 ms | 1.1 ms | 1324 MB |
| both back, the Nether and End closed after 300 idle ticks | 0.8 ms | 0.9 ms | 1335 MB |
- A level costs only while a player is in it: its chunks around that player, their entities, and the
tick. With nobody outside the Overworld, `tick_server` runs one pass, as before.
- A closed level's memory goes back to the allocator, not always to the system.
- Entering a level the first time opens its region files and streaming (`open_level`). That cost
comes once, before the player's chunks load.
## Saving
`save_game` saves the level in place, then every parked level (`save_parked_levels`). Each level has
its own region folder, as in vanilla (`DIM-1`, `DIM1`). A level closed for being idle is saved first.
Each player's saved data holds its dimension (`Dimension`). A guest who leaves in
the Nether, or whose host saves and quits, joins again in the Nether where it was.
## What's checked
`python3 tools/lan_e2e.py --server-thread --check portals --check levels`:
- `portals`: the guest goes to the Nether through a portal while the host stays. The host then goes
to the End while the guest is in the Nether, so three levels run at once, and both come back.
- `levels`, with the host and the guest each in a level of its own:
- `execute in the_nether run tp` moves the guest alone. From the Nether, `execute in overworld` and
`execute at` the host change and test blocks in the host's level.
- 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. 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
joins again there.
## Not done yet
- **End credits for server players.** The first exit from the End should show a player the credits
(`EndPortalBlock.entityInside`, `seenCredits`). The client's WinScreen is #338.
- **Entities through portals between levels.** Mobs, items and minecarts that enter a portal on a
server, and portal tickets (`TeleportTransition.PLACE_PORTAL_TICKET`), are not handled.
- **Unlimited selectors.** `@e` without a distance or volume reads only the source's level. Vanilla's
reads every level.
+1 -1
View File
@@ -90,7 +90,7 @@ not tick cost, so it is in scope here (see section 9).
|---|---|
| `online-mode=true` | **Works** (ServerLoginPacketListenerImpl): a 1024-bit RSA key pair at start ("Generating keypair"), the encryption request, the shared secret and challenge, AES/CFB8, and the session service's `hasJoined` check (with the address when `prevent-proxy-connections` is on), with vanilla's log lines and messages. `test_online_mode_parity.py` runs the same logins against vanilla's server and Horizon's with a mock session service. |
| Secure chat | **Works** (`SignedMessageChain`, `LastSeenMessagesValidator`, `MessageSignatureCache`): the chat session update and its profile key, checked against the services' `playerCertificateKeys`; signed chat, `say`, `me` and `msg`, relayed with their signatures and last-seen lists; `enforce-secure-profile` (with `online-mode`) refuses unsigned chat; and vanilla's log lines (`[Not Secure]`, the decoder's warnings, the kicks). Offline servers and players without a chat session chat unsigned, as on vanilla. `test_secure_chat_parity.py` runs the same signed and unsigned players against vanilla's server and Horizon's, with test keys and a mock services server. |
| Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. |
| Nether and End | **Works**: the server holds a level per dimension, and each player is in its own (portals, `execute in … tp`, respawn). `test_server_dimension_players_parity.py` checks it against vanilla. How it works, its cost and what's left: [server-levels.md](server-levels.md). |
| Refused logins | Logged as vanilla does: `Disconnecting <name> (/address): <reason>`, then `<name> (/address) lost connection: <reason>`, and the session errors (`Username '<name>' tried to join with an invalid session`, `Couldn't verify username because servers are unavailable`). |
| Gameplay for remote players | Checked against vanilla's server with a vanilla-codec client (#484, `tools/test_dedicated_server_parity.py`): a right click with an item on a block uses it once, a dead player's commands run, players on a team without friendly fire don't hurt each other, and a player's projectiles are theirs (their ender pearl takes them). The recipe book, status effects and block sync while digging (#500) work. Left: a player's projectiles don't hit other players (no bow PvP between guests), and a mob a guest kills counts in the host's statistics and advancements, not the guest's (`mob_died` runs as the host). |
| Defaults that surprise owners | `white-list=true` is vanilla 26.3's default, so a fresh server refuses everyone until they are added. That matches vanilla, so the first-run flow (section 3) asks about the whitelist up front. |
+299 -4
View File
@@ -67,6 +67,13 @@ address. The script then checks, from both sides, what a guest's game used to ge
- 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.
- 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, 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
tree (Tab), and runs what it completed;
- recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it
@@ -178,7 +185,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# 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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'absorption', 'breath', 'lava']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'absorption', 'breath', 'lava', 'levels']
class Game:
@@ -515,12 +522,17 @@ def portals(host, guest, out, x, y, z, hx, hy, hz):
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)
# On a server the guest is held where it entered until the chunks around the destination are
# lit, then placed in its portal: wait for that before reading where it arrived.
for _ in range(30):
guest.wait(20)
arrived = [int(v // 1) for v in pos_of(guest)]
if guest.raw('block', *arrived).get('block') == 'minecraft:nether_portal':
break
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.
@@ -548,6 +560,288 @@ def portals(host, guest, out, x, y, z, hx, hy, hz):
return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)}
NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld'
def check_levels(host, guest, out):
"""(--server-thread) Each player in its own level (MinecraftServer.levels), the host and the guest
apart: the steps run in order, each reported, and the check fails if any did."""
if not SERVER_THREAD:
return 'skipped (needs --server-thread)'
start = {g.name: pos_of(g) for g in (host, guest)}
steps, failed = {}, []
guest('command', command='gamemode creative')
try:
for name, step in LEVEL_STEPS:
try:
steps[name] = step(host, guest, out)
except (Failed, AssertionError, StopIteration, KeyError) as e:
steps[name], failed = repr(e), failed + [name]
for g in (host, guest):
back_to_game(g)
print(f'[lan] levels {name}: {"FAIL" if name in failed else "PASS"} {steps[name]}')
finally:
for g in (host, guest):
back_to_game(g)
if g('state').get('screen') == 'dead':
g.raw('respawn')
g.wait(20)
x, y, z = start[g.name]
g('command', command=f'execute in {OVERWORLD} run tp @s {x:.2f} {y:.2f} {z:.2f}')
guest('command', command='gamemode survival')
guest.wait(40)
assert not failed, f'failed: {failed}; {steps}'
return steps
def level_floor(game, x, y, z):
"""An obsidian floor under x y z with air above it, in the level `game` is in (fill needs the
chunks loaded: ServerLevel.hasChunksAt)."""
game('command', command=f'fill {x - 4} {y - 1} {z - 4} {x + 4} {y - 1} {z + 4} minecraft:obsidian')
game('command', command=f'fill {x - 4} {y} {z - 4} {x + 4} {y + 4} {z + 4} minecraft:air')
def into_level(game, dimension, x, y, z):
"""`execute in DIMENSION run tp` to x y z, onto a floor built once the level has loaded around it."""
game('command', command=f'execute in {dimension} run tp @s {x + 0.5} {y} {z + 0.5}')
state = wait_dimension(game, dimension, 400)
game.wait(20)
level_floor(game, x, y, z)
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
game.wait(20)
return state
def dims(host, guest):
return host('state').get('dimension'), guest('state').get('dimension')
def level_execute(host, guest, out):
"""`execute in the_nether run tp` takes the guest alone. From the Nether, the guest's commands
reach the host's level (CommandSourceStack.getLevel): `execute in overworld` and `execute at`
the host put a block beside the host, and `execute if block` reads it."""
x, z = (int(v // 1) for v in pos_of(guest)[::2])
hx, hy, hz = (int(v // 1) for v in pos_of(host))
there = into_level(guest, NETHER, x, 100, z)
below = guest.raw('block', x, 99, z)
gold = f'{hx} {hy} {hz + 2} minecraft:gold_block'
try:
guest('command', command=f'execute in {OVERWORLD} run setblock {gold}')
guest('command', command=f'execute at {host.player} run setblock ~ ~ ~-2 minecraft:diamond_block')
guest('command', command=f'execute in {OVERWORLD} if block {gold} in {NETHER} '
f'run setblock {x} 99 {z} minecraft:gold_block')
host.wait(10)
placed = [host.raw('block', hx, hy, hz + 2), host.raw('block', hx, hy, hz - 2)]
found = guest.raw('block', x, 99, z)
finally:
host('command', command=f'fill {hx} {hy} {hz - 2} {hx} {hy} {hz + 2} minecraft:air')
assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}'
assert there.get('dimension') == NETHER and below.get('block') == 'minecraft:obsidian', f'{there} on {below}'
assert [p.get('block') for p in placed] == ['minecraft:gold_block', 'minecraft:diamond_block'], \
f'beside the host: {placed}'
assert found.get('block') == 'minecraft:gold_block', f'execute in overworld if block: {found}'
return {'guest': pos_of(guest)}
def level_ticking(host, guest, out):
"""Mobs and objects fall in both levels at once (each level with a player ticks); every entity
has its own id across the levels."""
gx, gy, gz = pos_of(guest)
hx, hy, hz = pos_of(host)
# A floor of its own beside the host (earlier checks may have broken the open one there).
bx, by, bz = int(hx // 1), int(hy // 1), int(hz // 1)
host('command', command=f'fill {bx - 4} {by - 1} {bz - 4} {bx + 4} {by - 1} {bz - 2} minecraft:stone')
host('command', command=f'fill {bx - 4} {by} {bz - 4} {bx + 4} {by + 4} {bz - 2} minecraft:air')
guest('command', command=f'summon minecraft:pig {gx + 2.5:.2f} {gy + 3:.2f} {gz:.2f}')
guest('command', command=f'summon minecraft:armor_stand {gx - 2.5:.2f} {gy + 3:.2f} {gz:.2f}')
host('command', command=f'summon minecraft:pig {hx + 2.5:.2f} {hy + 3:.2f} {hz - 3:.2f}')
host('command', command=f'summon minecraft:armor_stand {hx - 2.5:.2f} {hy + 3:.2f} {hz - 3:.2f}')
try:
guest.wait(60)
seen = {}
for name, g, floor in (('guest', guest, gy), ('host', host, hy)):
mobs = [m for m in g.raw('mobs', 8)['near'] if m['kind'] == 'minecraft:pig']
stands = [o for o in g('status')['objects'] if o['kind'] == 'minecraft:armor_stand']
seen[name] = {'pigs': [(m['id'], round(m['pos'][1], 2)) for m in mobs],
'stands': [(o['id'], round(o['position'][1], 2)) for o in stands], 'floor': floor}
finally:
guest('command', command='kill @e[type=!minecraft:player,distance=..8]')
host('command', command='kill @e[type=!minecraft:player,distance=..8]')
for name, s in seen.items():
heights = [y for _, y in s['pigs'] + s['stands']]
assert len(s['pigs']) == 1 and len(s['stands']) == 1, f'{name} sees {s}'
assert all(abs(y - s['floor']) < 0.1 for y in heights), f"{name}'s did not fall to the floor: {seen}"
ids = [i for s in seen.values() for i, _ in s['pigs'] + s['stands']]
assert len(set(ids)) == len(ids), f'ids shared across the levels: {seen}'
return seen
def level_rejoin(host, guest, out):
"""The guest leaves in the Nether and joins again there (its player data keeps its level)."""
before = pos_of(guest)
port = host.raw('lan', 'status')['port']
guest.raw('disconnect')
time.sleep(2)
guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME)
guest.raw('wait-for', 'loaded', '--timeout', 300)
guest.wait(20)
after = pos_of(guest)
assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}'
assert all(abs(a - b) < 1 for a, b in zip(before, after)), f'left at {before}, back at {after}'
return {'at': after}
def level_death(host, guest, out):
"""The guest dies in the Nether and respawns in the Overworld; the host stays where it is."""
guest('command', command='kill @s')
guest.wait(20)
guest.raw('respawn')
back = wait_dimension(guest, OVERWORLD, 400)
guest.wait(20)
assert back.get('dimension') == OVERWORLD, f'the guest respawned in {back.get("dimension")}'
assert dims(host, guest) == (OVERWORLD, OVERWORLD), f'host, guest in {dims(host, guest)}'
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))
nether_portal(host, hx, hy, hz - 3)
try:
host('command', command=f'tp @s {hx + 0.5} {hy} {hz - 2.5}')
there = wait_dimension(host, NETHER, 600)
host.wait(20)
result = dims(host, guest)
assert there.get('dimension') == NETHER, f'the host is in {there.get("dimension")}'
assert result == (NETHER, OVERWORLD), f'host, guest in {result}'
return {'host': there['player']['position']}
finally:
host('command', command=f'execute in {OVERWORLD} run fill {hx - 1} {hy} {hz - 3} {hx + 2} {hy + 3} {hz - 3} '
'minecraft:air')
host('command', command=f'execute in {OVERWORLD} run tp @s {hx + 0.5} {hy} {hz + 0.5}')
wait_dimension(host, OVERWORLD, 400)
def level_guest_end(host, guest, out):
"""The guest steps into an End portal alone and lands on the obsidian platform, an End gateway
takes it across the End, and an exit portal takes it back to the Overworld."""
x, y, z = (int(v // 1) for v in pos_of(guest))
guest('command', command=f'setblock {x + 2} {y} {z} minecraft:end_portal')
try:
guest('command', command=f'tp @s {x + 2.5} {y} {z + 0.5}')
wait_dimension(guest, END, 600)
# The arrival waits for the platform's chunks; its portal cooldown (10 ticks) runs out after,
# and a player who stands in a portal while it runs stays (Entity.setAsInsidePortal).
guest.wait(60)
landed = pos_of(guest)
assert dims(host, guest) == (OVERWORLD, END), f'host, guest in {dims(host, guest)}'
assert [int(v // 1) for v in landed] == [100, 49, 0], f'the guest landed at {landed}'
finally:
guest('command', command=f'execute in {OVERWORLD} run setblock {x + 2} {y} {z} minecraft:air')
# A gateway far out with an exact exit at the End spawn, as end_gateway_return's
# (TheEndGatewayBlockEntity.getPortalPosition), takes the guest back there within the End.
guest('command', command='tp @s 700.5 80 0.5')
guest.wait(60)
level_floor(guest, 700, 80, 0)
guest('command', command='tp @s 700.5 80 0.5')
guest.wait(20)
guest('command', command='setblock 702 80 0 minecraft:end_gateway{exit_portal:[I;100,50,0],exact_teleport:1b}')
guest('command', command='tp @s 702.5 80 0.5')
gateway = None
for _ in range(20):
guest.wait(10)
gateway = pos_of(guest)
if abs(gateway[0] - 702.5) > 50:
break
assert dims(host, guest) == (OVERWORLD, END), f'host, guest in {dims(host, guest)}'
assert abs(gateway[0] - 100.5) < 1 and abs(gateway[2] - 0.5) < 1 and 49 <= gateway[1] <= 50, \
f'the gateway left the guest at {gateway}'
guest.wait(40)
ex, ey, ez = (int(v // 1) for v in pos_of(guest))
guest('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal')
guest('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}')
home = wait_dimension(guest, OVERWORLD, 600)
guest.wait(20)
assert dims(host, guest) == (OVERWORLD, OVERWORLD), f'host, guest in {dims(host, guest)}'
return {'landed': landed, 'gateway': gateway, 'home': home['player']['position']}
def level_reload(host, guest, out):
"""The host saves and quits with the guest in the Nether, opens the world again and opens it to the
LAN; the guest joins again where it was, in the Nether."""
x, z = (int(v // 1) for v in pos_of(guest)[::2])
into_level(guest, NETHER, x, 100, z)
before = pos_of(guest)
host.raw('disconnect')
# The world saves on its server thread before the title screen shows.
for attempt in range(60):
time.sleep(1)
try:
host.raw('open', 'Lan')
break
except Failed:
if attempt == 59:
raise
host('wait_ready', seconds=400)
port = host.raw('lan', 'open', 0, 'commands')['port']
back_to_game(guest)
guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME)
guest.raw('wait-for', 'loaded', '--timeout', 300)
guest.wait(20)
after = pos_of(guest)
assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}'
assert all(abs(a - b) < 1 for a, b in zip(before, after)), f'left at {before}, back at {after}'
return {'at': after}
LEVEL_STEPS = [('execute', level_execute), ('ticking', level_ticking), ('rejoin', level_rejoin),
('death', level_death), ('respawn_points', level_respawn_points),
('host_nether', level_host_nether),
('guest_end', level_guest_end), ('reload', level_reload)]
def check_damage(host, guest, out):
guest('command', command='gamemode survival')
guest.wait(10)
@@ -3193,7 +3487,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'light': check_light, 'plates': check_plates,
'swings': check_swings, 'cracks': check_cracks,
'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts,
'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava}
'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava,
'levels': check_levels}
def run(ctl, out, resources, checks):