Merge branch 'fix/items-out-of-blocks' into fix/mob-knockback-view
This commit is contained in:
@@ -22,6 +22,11 @@ impl PlayerMotion {
|
||||
pub fn refresh_attributes(&mut self) -> Result<()> {
|
||||
live_updates::refresh(self)
|
||||
}
|
||||
/// `Player.internalSetAbsorptionAmount`: the amount as given, unclamped
|
||||
/// (the saved `AbsorptionAmount`, or what a client's server sent).
|
||||
pub fn internal_set_absorption(&mut self, value: f32) -> Result<()> {
|
||||
self.store_absorption(value)
|
||||
}
|
||||
}
|
||||
impl HealthWorld for PlayerMotion {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,12 +98,73 @@ impl ItemEntity {
|
||||
lava_hurt,
|
||||
}
|
||||
}
|
||||
/// Returns false when the item should be removed.
|
||||
/// `ItemEntity.tick` on a server: an item whose box is inside a block
|
||||
/// (one placed where it lay) has no physics this tick
|
||||
/// (`level.noCollision(box.deflate(1.0E-7))`).
|
||||
pub fn inside_block(&self, world: &World, collision: &BlockCollisionRegistry<'_>) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world,
|
||||
binding: collision,
|
||||
subject: None,
|
||||
};
|
||||
let inner = self.bounds().deflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7));
|
||||
!crate::collisions::no_collision_empty(&mut scene, inner)
|
||||
}
|
||||
/// `Entity.moveTowardsClosestSpace` from the middle of the item's box:
|
||||
/// towards the nearest side of its block (north, south, west, east or
|
||||
/// up) without a full collision cube, at `speed` (`nextFloat() * 0.2 +
|
||||
/// 0.1`).
|
||||
pub fn move_towards_closest_space(&mut self, world: &World, facts: &BlockFacts, speed: f32) {
|
||||
let bounds = self.bounds();
|
||||
let at = Vec3::new(
|
||||
self.position.x,
|
||||
(bounds.min_position().y + bounds.max_position().y) / 2.0,
|
||||
self.position.z,
|
||||
);
|
||||
let pos = [
|
||||
at.x.floor() as i32,
|
||||
at.y.floor() as i32,
|
||||
at.z.floor() as i32,
|
||||
];
|
||||
let delta = [
|
||||
at.x - f64::from(pos[0]),
|
||||
at.y - f64::from(pos[1]),
|
||||
at.z - f64::from(pos[2]),
|
||||
];
|
||||
// (axis, step): NORTH, SOUTH, WEST, EAST, UP.
|
||||
let mut closest = (1, 1);
|
||||
let mut nearest = f64::MAX;
|
||||
for (axis, step) in [(2, -1), (2, 1), (0, -1), (0, 1), (1, 1)] {
|
||||
let mut n = pos;
|
||||
n[axis] += step;
|
||||
if !facts.get(world.block(n[0], n[1], n[2])).full_collision {
|
||||
let d = if step > 0 {
|
||||
1.0 - delta[axis]
|
||||
} else {
|
||||
delta[axis]
|
||||
};
|
||||
if d < nearest {
|
||||
nearest = d;
|
||||
closest = (axis, step);
|
||||
}
|
||||
}
|
||||
}
|
||||
let push = f64::from(closest.1 as f32 * speed);
|
||||
let v = self.velocity.scale(0.75);
|
||||
self.velocity = match closest.0 {
|
||||
0 => Vec3::new(push, v.y, v.z),
|
||||
1 => Vec3::new(v.x, push, v.z),
|
||||
_ => Vec3::new(v.x, v.y, push),
|
||||
};
|
||||
}
|
||||
/// Returns false when the item should be removed. `no_physics`: the item
|
||||
/// moves through blocks this tick ([`ItemEntity::inside_block`]).
|
||||
pub fn tick(
|
||||
&mut self,
|
||||
world: &World,
|
||||
facts: &BlockFacts,
|
||||
collision: &BlockCollisionRegistry<'_>,
|
||||
no_physics: bool,
|
||||
) -> bool {
|
||||
self.ticks += 1;
|
||||
self.previous = self.position;
|
||||
@@ -140,15 +201,22 @@ impl ItemEntity {
|
||||
subject: None,
|
||||
};
|
||||
let wanted = self.velocity;
|
||||
let moved = scene
|
||||
.resolve(self.bounds(), wanted, 0.0, self.on_ground)
|
||||
.unwrap_or(Vec3::ZERO);
|
||||
// Entity.move with noPhysics: straight through, the ground as it was.
|
||||
let moved = if no_physics {
|
||||
wanted
|
||||
} else {
|
||||
scene
|
||||
.resolve(self.bounds(), wanted, 0.0, self.on_ground)
|
||||
.unwrap_or(Vec3::ZERO)
|
||||
};
|
||||
self.position = Vec3::new(
|
||||
self.position.x + moved.x,
|
||||
self.position.y + moved.y,
|
||||
self.position.z + moved.z,
|
||||
);
|
||||
self.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
|
||||
if !no_physics {
|
||||
self.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
|
||||
}
|
||||
if moved.x != wanted.x {
|
||||
self.velocity.x = 0.0;
|
||||
}
|
||||
|
||||
+821
-225
File diff suppressed because it is too large
Load Diff
@@ -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,
|
||||
@@ -2101,7 +2106,14 @@ impl Game<'_> {
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let alive = item.tick(&self.world, self.res.facts(), self.collision);
|
||||
// ItemEntity.tick's noPhysics (servers only): out of a block
|
||||
// placed on it, towards the closest open side (#1252).
|
||||
let no_physics = merging && item.inside_block(&self.world, self.collision);
|
||||
if no_physics {
|
||||
let speed = self.world.random.next_float() * 0.2 + 0.1;
|
||||
item.move_towards_closest_space(&self.world, self.res.facts(), speed);
|
||||
}
|
||||
let alive = item.tick(&self.world, self.res.facts(), self.collision, no_physics);
|
||||
cells.moved(i, item.previous, item.position);
|
||||
// ItemEntity.tick: merge every 2 ticks while moving between
|
||||
// blocks, every 40 otherwise, before the lifetime check.
|
||||
@@ -3581,8 +3593,6 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
fn tick_using(&mut self) {
|
||||
// ItemCooldowns.tick for the shield.
|
||||
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
|
||||
let Some(hand) = self.used_hand() else {
|
||||
return;
|
||||
};
|
||||
@@ -3798,6 +3808,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,
|
||||
@@ -4285,6 +4298,9 @@ impl Game<'_> {
|
||||
fn tick_world(&mut self, running: bool) -> Result<()> {
|
||||
self.update_chunk_tickets();
|
||||
horizon_client::spans::time("tick_effects", || self.tick_effects());
|
||||
// Player.tick's ItemCooldowns.tick for the window's player (a
|
||||
// server's players count theirs down in `tick_guests`).
|
||||
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
|
||||
horizon_client::spans::time("tick_using", || self.tick_using());
|
||||
horizon_client::spans::time("tick_hud", || self.tick_hud());
|
||||
// The player's digging comes in with its packets, before the level
|
||||
@@ -4485,7 +4501,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 +4717,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 +4955,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 +7540,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 +9522,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;
|
||||
@@ -9516,6 +9530,7 @@ impl Game<'_> {
|
||||
if let Some(p) = &self.player {
|
||||
level.position = Some([p.position.x, p.position.y, p.position.z]);
|
||||
level.health = p.health.health();
|
||||
level.absorption = p.health.absorption();
|
||||
let extra = level
|
||||
.player_extra
|
||||
.get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default()));
|
||||
@@ -10098,12 +10113,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)
|
||||
}
|
||||
@@ -10187,6 +10203,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
|
||||
@@ -10786,7 +10803,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()
|
||||
@@ -10844,6 +10863,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)?;
|
||||
@@ -11100,6 +11120,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)
|
||||
}
|
||||
@@ -11233,6 +11256,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());
|
||||
@@ -11660,6 +11684,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(),
|
||||
|
||||
@@ -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> {
|
||||
@@ -459,8 +460,11 @@ impl Game<'_> {
|
||||
"sneaking": self.keys.contains(&KeyCode::ShiftLeft),
|
||||
"sprinting": self.keys.contains(&KeyCode::ControlLeft),
|
||||
"health": p.health.health(),
|
||||
"absorption": p.health.absorption(),
|
||||
"air": p.air,
|
||||
"food": p.health.food.food,
|
||||
"saturation": p.health.food.saturation,
|
||||
"shield_cooldown": self.shield_cooldown,
|
||||
"xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total },
|
||||
"effects": self.potions.effects.list.iter().map(|e| json!({ "id": e.id, "duration_ticks": e.duration, "amplifier": e.amplifier })).collect::<Vec<_>>(),
|
||||
})
|
||||
@@ -478,6 +482,8 @@ impl Game<'_> {
|
||||
"sleeping": self.sleeping,
|
||||
// The item in use: its slot and for how many ticks.
|
||||
"using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })),
|
||||
// The block being dug: how far along, after how many ticks.
|
||||
"mining": self.mining.as_ref().map(|m| json!({ "pos": m.pos, "progress": m.progress, "ticks": m.ticks })),
|
||||
// The arm swings started (LivingEntity.swing).
|
||||
"swings": self.swings_started,
|
||||
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
|
||||
|
||||
@@ -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![
|
||||
@@ -2322,7 +2337,19 @@ impl Game<'_> {
|
||||
Some(Arg::Coords(c)) => c.rotation(self.source_rotation()),
|
||||
_ => [0.0, 0.0],
|
||||
};
|
||||
self.level.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]);
|
||||
// LevelData.setRespawnData: the world's spawn (level.dat `spawn`).
|
||||
let old = self.level.world_spawn.replace(pos);
|
||||
self.level.world_spawn_angle = rot;
|
||||
// A player whose respawn point is the world spawn (no bed, anchor or
|
||||
// spawnpoint of its own) respawns at the new one.
|
||||
let floor = |s: Vec3| [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32];
|
||||
if self.respawn_config.is_none() && self.spawn.map(floor) == old {
|
||||
self.spawn = Some(Vec3::new(
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
));
|
||||
}
|
||||
let args = [
|
||||
Text::literal(pos[0].to_string()),
|
||||
Text::literal(pos[1].to_string()),
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -390,9 +390,14 @@ impl Game<'_> {
|
||||
"placed": g.placed,
|
||||
"loaded": g.loaded,
|
||||
"game_mode": g.game_mode,
|
||||
// ItemCooldowns: the ticks the shield an axe disabled stays down.
|
||||
"shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown),
|
||||
"sneaking": g.sneaking,
|
||||
"sleeping": g.bed,
|
||||
"health": g.health,
|
||||
// The server's body: its air supply and golden hearts.
|
||||
"air": g.motion.as_ref().map(|m| m.air),
|
||||
"absorption": g.motion.as_ref().map(|m| m.health.absorption()),
|
||||
// FoodData: food level, saturation and exhaustion.
|
||||
"food": [
|
||||
f64::from(g.food),
|
||||
|
||||
@@ -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,
|
||||
@@ -34,6 +34,8 @@ pub(super) struct GuestPlay {
|
||||
destroy_delay: u32,
|
||||
using: Option<(usize, u32)>,
|
||||
use_delay: u32,
|
||||
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
|
||||
pub(super) shield_cooldown: u32,
|
||||
attack_ticks: u32,
|
||||
/// The main hand's item at the guest's last tick (`Game::attack_item`).
|
||||
attack_item: Option<std::sync::Arc<str>>,
|
||||
@@ -117,6 +119,7 @@ pub(super) struct GuestSwap {
|
||||
destroy_delay: u32,
|
||||
using: Option<(usize, u32)>,
|
||||
use_delay: u32,
|
||||
pub(super) shield_cooldown: u32,
|
||||
attack_ticks: u32,
|
||||
attack_item: Option<std::sync::Arc<str>>,
|
||||
swing: horizon_client::first_person::SwingState,
|
||||
@@ -217,6 +220,12 @@ impl Game<'_> {
|
||||
host.hub.guests[i].position[2],
|
||||
);
|
||||
host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new);
|
||||
// The saved golden hearts go on the first body of a player who
|
||||
// has been here before.
|
||||
let saved = host.hub.guests[i].saved_absorption.take();
|
||||
if let (Some(m), Some(amount)) = (host.hub.guests[i].motion.as_mut(), saved) {
|
||||
let _ = m.internal_set_absorption(amount);
|
||||
}
|
||||
let kept = host.hub.guests[i].logs_kept.take();
|
||||
if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) {
|
||||
m.hurt_log = hurts;
|
||||
@@ -290,6 +299,7 @@ impl Game<'_> {
|
||||
let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay);
|
||||
let using = std::mem::replace(&mut self.using, play.using.take());
|
||||
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
|
||||
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
|
||||
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
|
||||
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
|
||||
let swing = std::mem::replace(&mut self.swing, play.swing);
|
||||
@@ -309,6 +319,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.
|
||||
@@ -369,6 +380,7 @@ impl Game<'_> {
|
||||
destroy_delay,
|
||||
using,
|
||||
use_delay,
|
||||
shield_cooldown,
|
||||
attack_ticks,
|
||||
attack_item,
|
||||
swing,
|
||||
@@ -421,6 +433,7 @@ impl Game<'_> {
|
||||
destroy_delay,
|
||||
using,
|
||||
use_delay,
|
||||
shield_cooldown,
|
||||
attack_ticks,
|
||||
attack_item,
|
||||
swing,
|
||||
@@ -470,7 +483,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);
|
||||
@@ -480,6 +494,7 @@ impl Game<'_> {
|
||||
play.destroy_delay = std::mem::replace(&mut self.destroy_delay, destroy_delay);
|
||||
play.using = std::mem::replace(&mut self.using, using);
|
||||
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
|
||||
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
|
||||
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
|
||||
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
|
||||
play.swing = std::mem::replace(&mut self.swing, swing);
|
||||
@@ -507,6 +522,7 @@ impl Game<'_> {
|
||||
g.vehicle = guest_vehicle;
|
||||
let fell_asleep = bed.is_some() && g.bed.is_none();
|
||||
(g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn);
|
||||
g.respawn_elsewhere = guest_respawn.map(|c| c.saved());
|
||||
g.sleeping = g.bed.is_some();
|
||||
if let Some((text, _)) = guest_message {
|
||||
g.send(&C::SystemChat(play::SystemChat {
|
||||
@@ -1486,17 +1502,32 @@ impl Game<'_> {
|
||||
if !host.hub.guests[i].dead {
|
||||
return;
|
||||
}
|
||||
// PlayerList.respawn: a server's player comes back in the Overworld,
|
||||
// where the world spawn is (respawn anchors and beds aside).
|
||||
// PlayerList.respawn: a server's player comes back in its respawn
|
||||
// point's level: the Overworld, where the world spawn and beds are,
|
||||
// or another one's anchor or forced point, which its block resolves
|
||||
// once the level has loaded around it.
|
||||
let server = self.options.dedicated.is_some();
|
||||
let elsewhere = host.hub.guests[i]
|
||||
.respawn_elsewhere
|
||||
.as_ref()
|
||||
.filter(|_| server)
|
||||
.map(RespawnConfig::from_saved);
|
||||
let level = elsewhere.map_or(super::Dim::Overworld, |c| c.dim);
|
||||
let spawn = elsewhere.map_or(spawn, |c| {
|
||||
[
|
||||
f64::from(c.pos[0]) + 0.5,
|
||||
f64::from(c.pos[1]),
|
||||
f64::from(c.pos[2]) + 0.5,
|
||||
]
|
||||
});
|
||||
let back = self.dim;
|
||||
let away = self.options.dedicated.is_some()
|
||||
&& host.hub.guests[i].dimension != super::Dim::Overworld.id();
|
||||
if away {
|
||||
let away = server && host.hub.guests[i].dimension != level.id();
|
||||
if server {
|
||||
self.server_trips.retain(|t| !t.is(conn));
|
||||
if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) {
|
||||
log::error!("could not open the Overworld: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if away && let Err(e) = self.enter_level(Some(host), level) {
|
||||
log::error!("could not open {}: {e}", level.id());
|
||||
return;
|
||||
}
|
||||
let g = &mut host.hub.guests[i];
|
||||
g.dead = false;
|
||||
@@ -1535,6 +1566,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());
|
||||
}
|
||||
@@ -1562,6 +1596,9 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
let play = host.play.entry(conn).or_default();
|
||||
// Player.tick's ItemCooldowns.tick, once a tick for each player
|
||||
// (the shield an axe disabled).
|
||||
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
|
||||
let digging = play.digging;
|
||||
let using = play.using.is_some();
|
||||
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
||||
@@ -1616,6 +1653,9 @@ impl Game<'_> {
|
||||
self.guest_dig_feedback(host, conn);
|
||||
self.guest_pickups(host, gi);
|
||||
self.guest_orbs(host, gi);
|
||||
if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead {
|
||||
self.guest_forget_digging(host, conn);
|
||||
}
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if g.health <= 0.0 && !g.dead {
|
||||
g.dead = true;
|
||||
@@ -1765,6 +1805,7 @@ impl Game<'_> {
|
||||
}
|
||||
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
|
||||
let at = g.position;
|
||||
let sneaking = g.sneaking;
|
||||
let sounds = self.as_guest(host, conn, |game| {
|
||||
let (rules, motion) = (game.world.health_rules, game.motion);
|
||||
let health = &motion.health;
|
||||
@@ -1783,6 +1824,26 @@ impl Game<'_> {
|
||||
let _ = w.fluid_base_tick();
|
||||
w.player.ground.on_ground = from_ground;
|
||||
let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect();
|
||||
// Entity.move's movementThisTick: each move, from where the
|
||||
// tick's first one started.
|
||||
let end = w.player.position;
|
||||
let start = travelled
|
||||
.iter()
|
||||
.fold(end, |p, d| p.subtract(Vec3::new(d[0], d[1], d[2])));
|
||||
w.player.history.clear();
|
||||
let mut from = start;
|
||||
for d in &travelled {
|
||||
let delta = Vec3::new(d[0], d[1], d[2]);
|
||||
let to = from.add_vector(delta);
|
||||
w.player
|
||||
.history
|
||||
.add(horizon_world::entity_move::MovementRecord {
|
||||
from,
|
||||
to,
|
||||
original: Some(delta),
|
||||
});
|
||||
from = to;
|
||||
}
|
||||
for (moved, on_ground) in moves {
|
||||
let movement = Vec3::new(moved[0], moved[1], moved[2]);
|
||||
if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 {
|
||||
@@ -1808,6 +1869,10 @@ impl Game<'_> {
|
||||
if w.climbable().unwrap_or(false) {
|
||||
w.player.fall_distance = 0.0;
|
||||
}
|
||||
// Entity.applyEffectsFromBlocks along those moves: magma, cactus,
|
||||
// lit campfires and grown sweet berry bushes hurt (#1305).
|
||||
w.player.shift_key_down = sneaking;
|
||||
let _ = w.server_block_damage(start);
|
||||
let _ = w.tick_environment_damage();
|
||||
let _ = w.apply_fire_contact();
|
||||
let _ = w.server_hazards_tick(in_wall);
|
||||
@@ -1968,6 +2033,23 @@ impl Game<'_> {
|
||||
|
||||
/// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the
|
||||
/// host and the other guests.
|
||||
/// A player who dies digs and uses nothing any more: the block it was
|
||||
/// breaking, or had left to break (`hasDelayedDestroy`), stays, and its
|
||||
/// crack goes. Respawning gives it a new ServerPlayerGameMode (#1315).
|
||||
fn guest_forget_digging(&mut self, host: &mut LanHost, conn: u32) {
|
||||
let Some(play) = host.play.get_mut(&conn) else {
|
||||
return;
|
||||
};
|
||||
let cracked = play.digging.take().filter(|_| play.last_progress >= 0);
|
||||
play.mining = None;
|
||||
play.delayed = None;
|
||||
play.destroy_delay = 0;
|
||||
play.using = None;
|
||||
play.last_progress = -1;
|
||||
if let Some((pos, _)) = cracked {
|
||||
self.guest_crack_gone(host, conn, pos);
|
||||
}
|
||||
}
|
||||
fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) {
|
||||
let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else {
|
||||
return;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -1964,11 +1964,27 @@ impl Game<'_> {
|
||||
// player lies down in the bed, or gets up.
|
||||
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
|
||||
for (index, _, value) in &p.values {
|
||||
if let (14, Value::OptPos(bed)) = (index, value) {
|
||||
if bed.is_some() && self.sleeping.is_none() {
|
||||
self.sleep_timer = 0;
|
||||
match (index, value) {
|
||||
(14, Value::OptPos(bed)) => {
|
||||
if bed.is_some() && self.sleeping.is_none() {
|
||||
self.sleep_timer = 0;
|
||||
}
|
||||
self.sleeping = *bed;
|
||||
}
|
||||
self.sleeping = *bed;
|
||||
// Entity.DATA_AIR_SUPPLY_ID and
|
||||
// Player.DATA_PLAYER_ABSORPTION_ID: the bubbles
|
||||
// and golden hearts the server's player has.
|
||||
(1, Value::Int(air)) => {
|
||||
if let Some(pl) = self.player.as_mut() {
|
||||
pl.air = *air;
|
||||
}
|
||||
}
|
||||
(17, Value::Float(amount)) => {
|
||||
if let Some(pl) = self.player.as_mut() {
|
||||
let _ = pl.internal_set_absorption(*amount);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2214,6 +2230,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);
|
||||
@@ -3094,6 +3114,13 @@ impl Game<'_> {
|
||||
);
|
||||
let was_flying = player.flying;
|
||||
player.yaw = self.yaw;
|
||||
// As the window's own tick has them: the helmet's Respiration
|
||||
// (decreaseAirSupply) and the dimension's FAST_LAVA, the Nether's
|
||||
// stronger lava current.
|
||||
player.respiration = self.armor[0]
|
||||
.as_ref()
|
||||
.map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32);
|
||||
player.fluids.fast_lava = self.dim == Dim::Nether;
|
||||
let dead = self.screen == Screen::Dead;
|
||||
// LivingEntity.isImmobile: a sleeper lies still in the bed.
|
||||
if let Some(head) = self.sleeping {
|
||||
@@ -3557,22 +3584,13 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
let facts = self.res.facts().get(state).clone();
|
||||
let held = self.held().cloned();
|
||||
let mut speed = self.res.items().mining_speed(held.as_ref(), &facts.name);
|
||||
if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) {
|
||||
speed /= 5.0;
|
||||
}
|
||||
let harvest = !facts.requires_tool
|
||||
|| self
|
||||
.res
|
||||
.items()
|
||||
.correct_for_drops(held.as_ref(), &facts.name);
|
||||
let progress = if facts.hardness < 0.0 {
|
||||
0.0
|
||||
} else if facts.hardness == 0.0 {
|
||||
// The server's own getDestroyProgress: under water, off the ground,
|
||||
// with haste, fatigue and efficiency, so the client stops digging
|
||||
// when the server is done too (#1254).
|
||||
let progress = if facts.hardness == 0.0 {
|
||||
1.0
|
||||
} else {
|
||||
speed / facts.hardness / if harvest { 30.0 } else { 100.0 }
|
||||
self.destroy_progress(hit.pos)
|
||||
};
|
||||
let same = self
|
||||
.remote
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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)] {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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])>,
|
||||
@@ -149,6 +153,9 @@ pub struct Guest {
|
||||
/// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots).
|
||||
pub ender_items: Vec<Option<ItemStack>>,
|
||||
pub health: f32,
|
||||
/// The saved `AbsorptionAmount`, until the player's first body on the
|
||||
/// server takes it (the body holds the live amount).
|
||||
pub saved_absorption: Option<f32>,
|
||||
pub food: i32,
|
||||
pub saturation: f32,
|
||||
pub xp_level: i32,
|
||||
@@ -168,6 +175,10 @@ pub struct Guest {
|
||||
/// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`.
|
||||
pub sent_health: Option<(f32, i32, bool)>,
|
||||
pub sent_xp: Option<(f32, i32, i32)>,
|
||||
/// The air supply and absorption the player's client was last sent
|
||||
/// (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID); their
|
||||
/// defaults until either changes.
|
||||
pub sent_air: (i32, f32),
|
||||
/// Where the player last died (Player.lastDeathLocation), sent with the respawn.
|
||||
pub last_death: Option<[i32; 3]>,
|
||||
/// The last action sequence to acknowledge at the next tick (-1: none).
|
||||
@@ -252,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,
|
||||
@@ -280,6 +292,7 @@ impl Guest {
|
||||
craft_result: None,
|
||||
ender_items: vec![None; 27],
|
||||
health: 20.0,
|
||||
saved_absorption: None,
|
||||
food: 20,
|
||||
saturation: 5.0,
|
||||
xp_level: 0,
|
||||
@@ -292,6 +305,7 @@ impl Guest {
|
||||
menu_state: 0,
|
||||
sent_health: None,
|
||||
sent_xp: None,
|
||||
sent_air: (300, 0.0),
|
||||
last_death: None,
|
||||
ack_up_to: std::cell::Cell::new(-1),
|
||||
sent_selected: 0,
|
||||
|
||||
@@ -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,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -1756,6 +1771,27 @@ impl Hub {
|
||||
}));
|
||||
}
|
||||
}
|
||||
// ServerEntity.sendDirtyEntityData: the air supply and the absorption
|
||||
// amount the server's body changed go to the player, whose HUD draws
|
||||
// them (bubbles, golden hearts).
|
||||
let g = &mut self.guests[i];
|
||||
if let Some(m) = g.motion.as_ref() {
|
||||
let now = (m.air, m.health.absorption());
|
||||
let mut values = Vec::new();
|
||||
if now.0 != g.sent_air.0 {
|
||||
values.push((1, serializer::INT, Value::Int(now.0)));
|
||||
}
|
||||
if now.1.to_bits() != g.sent_air.1.to_bits() {
|
||||
values.push((17, serializer::FLOAT, Value::Float(now.1)));
|
||||
}
|
||||
if !values.is_empty() {
|
||||
g.sent_air = now;
|
||||
g.send(&C::SetEntityData(play::SetEntityData {
|
||||
id: g.entity_id,
|
||||
values,
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Sent when the health or the food level changes, or the saturation
|
||||
// reaches or leaves zero; a dead player's health of 0 too.
|
||||
let g = &mut self.guests[i];
|
||||
@@ -2466,9 +2502,11 @@ impl Hub {
|
||||
global: false,
|
||||
}));
|
||||
}
|
||||
// lastSentExp, lastSentHealth and lastSentFood.
|
||||
// lastSentExp, lastSentHealth and lastSentFood; the client's new
|
||||
// player starts with the default air and no absorption.
|
||||
g.sent_health = None;
|
||||
g.sent_xp = None;
|
||||
g.sent_air = (300, 0.0);
|
||||
let (cx, cz) = g.chunk();
|
||||
g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter {
|
||||
x: cx,
|
||||
|
||||
@@ -61,6 +61,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
guest.head_yaw = guest.yaw;
|
||||
guest.on_ground = level.on_ground;
|
||||
guest.health = level.health;
|
||||
guest.saved_absorption = Some(level.absorption);
|
||||
guest.food = level.food;
|
||||
guest.saturation = level.saturation;
|
||||
guest.xp_level = level.xp_level;
|
||||
@@ -71,7 +72,13 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
guest.game_mode = level.mode();
|
||||
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]);
|
||||
// A point that is the world spawn is none of the player's own: it
|
||||
// respawns wherever the world spawn is then (`setworldspawn`).
|
||||
guest.spawn = level
|
||||
.spawn
|
||||
.filter(|s| Some(s.map(|v| v.floor() as i32)) != level.world_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() {
|
||||
@@ -123,6 +130,12 @@ pub fn store(guest: &Guest, level: &mut Level) {
|
||||
level.dimension = guest.dimension.clone();
|
||||
level.rotation = [guest.yaw, guest.pitch];
|
||||
level.health = guest.health;
|
||||
level.absorption = guest
|
||||
.motion
|
||||
.as_ref()
|
||||
.map_or(guest.saved_absorption.unwrap_or(0.0), |m| {
|
||||
m.health.absorption()
|
||||
});
|
||||
level.food = guest.food;
|
||||
level.saturation = guest.saturation;
|
||||
level.xp_level = guest.xp_level;
|
||||
@@ -135,6 +148,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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -338,6 +338,8 @@ impl PlayerMotion {
|
||||
.and_then(|t| crate::save::number(t.get("Air")))
|
||||
.unwrap_or(300) as i32;
|
||||
self.set_health(level.health, false)?;
|
||||
// LivingEntity.readAdditionalSaveData: internalSetAbsorptionAmount.
|
||||
self.internal_set_absorption(level.absorption)?;
|
||||
self.health.food.food = level.food;
|
||||
self.health.food.saturation = level.saturation;
|
||||
self.flying = level.flying;
|
||||
@@ -1029,9 +1031,22 @@ impl MotionWorld<'_, '_, '_> {
|
||||
}
|
||||
/// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts
|
||||
/// to inside its movement path: powder snow (`PowderSnowBlock.entityInside`
|
||||
/// and the FREEZE / EXTINGUISH effects), cobwebs and sweet berry bushes. Pressure plates, tripwires and
|
||||
/// rails are the world tick's scan.
|
||||
/// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes,
|
||||
/// cactus and lit campfires, and the magma block it stands on
|
||||
/// (`stepOn`). Pressure plates, tripwires and rails are the world tick's
|
||||
/// scan.
|
||||
pub fn apply_effects_from_blocks(&mut self) -> Result<()> {
|
||||
self.effects_from_blocks(false)
|
||||
}
|
||||
/// What `applyEffectsFromBlocks` does to a server's player along the
|
||||
/// moves its client sent since `from` (in its history): the damage of
|
||||
/// magma, cactus, lit campfires and grown sweet berry bushes. Its client
|
||||
/// moves it, so the slowing and the rest are the client's.
|
||||
pub fn server_block_damage(&mut self, from: Vec3) -> Result<()> {
|
||||
self.player.old_position = from;
|
||||
self.effects_from_blocks(true)
|
||||
}
|
||||
fn effects_from_blocks(&mut self, damage_only: bool) -> Result<()> {
|
||||
use horizon_world::entity_move::MovementRecord;
|
||||
let mut movements: Vec<MovementRecord> =
|
||||
self.player.history.records().iter().copied().collect();
|
||||
@@ -1056,6 +1071,19 @@ impl MotionWorld<'_, '_, '_> {
|
||||
if self.player.spectator {
|
||||
return Ok(());
|
||||
}
|
||||
// Block.stepOn for the block under an entity on the ground:
|
||||
// MagmaBlock's hot floor hurts unless it steps carefully (sneaks).
|
||||
if self.player.ground.on_ground {
|
||||
let on = self.legacy_on_position()?;
|
||||
let magma = self
|
||||
.assets
|
||||
.registry
|
||||
.state(self.block(on))
|
||||
.is_some_and(|s| s.name == "minecraft:magma_block");
|
||||
if magma && !self.player.shift_key_down {
|
||||
self.environment_hurt("minecraft:hot_floor", 1.0)?;
|
||||
}
|
||||
}
|
||||
let mut visited = std::collections::HashSet::new();
|
||||
let mut entered = Vec::new();
|
||||
for movement in &movements {
|
||||
@@ -1081,6 +1109,7 @@ impl MotionWorld<'_, '_, '_> {
|
||||
&mut visited,
|
||||
&mut entered,
|
||||
budget,
|
||||
damage_only,
|
||||
)?;
|
||||
from = to;
|
||||
}
|
||||
@@ -1093,11 +1122,19 @@ impl MotionWorld<'_, '_, '_> {
|
||||
&mut visited,
|
||||
&mut entered,
|
||||
16,
|
||||
damage_only,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if budget <= 0 {
|
||||
self.check_inside_blocks(movement.to, movement.to, &mut visited, &mut entered, 1)?;
|
||||
self.check_inside_blocks(
|
||||
movement.to,
|
||||
movement.to,
|
||||
&mut visited,
|
||||
&mut entered,
|
||||
1,
|
||||
damage_only,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
// InsideBlockEffectApplier.StepBasedCollector: the blocks entered
|
||||
@@ -1137,6 +1174,7 @@ impl MotionWorld<'_, '_, '_> {
|
||||
visited: &mut std::collections::HashSet<i64>,
|
||||
entered: &mut Vec<(i32, BlockPos)>,
|
||||
max_iterations: i32,
|
||||
damage_only: bool,
|
||||
) -> Result<i32> {
|
||||
let deflated = self.player.dimensions.bounds(to).deflate(Vec3::new(
|
||||
f64::from(1.0e-5_f32),
|
||||
@@ -1213,6 +1251,33 @@ impl MotionWorld<'_, '_, '_> {
|
||||
}
|
||||
};
|
||||
if inside && visited.insert(p.pack()) {
|
||||
// CactusBlock and CampfireBlock.entityInside (`entity.hurt`).
|
||||
match name {
|
||||
"minecraft:cactus" => self.environment_hurt("minecraft:cactus", 1.0)?,
|
||||
"minecraft:campfire" | "minecraft:soul_campfire" => {
|
||||
let lit = self
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("lit"))
|
||||
.is_some_and(|v| v == "true");
|
||||
let damage = if name == "minecraft:campfire" {
|
||||
1.0
|
||||
} else {
|
||||
2.0
|
||||
};
|
||||
if lit {
|
||||
self.environment_hurt("minecraft:campfire", damage)?;
|
||||
}
|
||||
}
|
||||
"minecraft:sweet_berry_bush" if damage_only => {
|
||||
self.sweet_berry_bush_damage(state)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if damage_only {
|
||||
continue;
|
||||
}
|
||||
match name {
|
||||
"minecraft:powder_snow" => {
|
||||
self.powder_snow_inside(p)?;
|
||||
@@ -1261,6 +1326,10 @@ impl MotionWorld<'_, '_, '_> {
|
||||
/// is at least 0.003 on X or Z.
|
||||
fn sweet_berry_bush_inside(&mut self, state: BlockStateId) -> Result<()> {
|
||||
self.make_stuck_in_block(Vec3::new(f64::from(0.8_f32), 0.75, f64::from(0.8_f32)));
|
||||
self.sweet_berry_bush_damage(state)
|
||||
}
|
||||
/// The server's half of `SweetBerryBushBlock.entityInside`: the prick.
|
||||
fn sweet_berry_bush_damage(&mut self, state: BlockStateId) -> Result<()> {
|
||||
let age = self
|
||||
.assets
|
||||
.registry
|
||||
|
||||
@@ -6,7 +6,7 @@ use horizon_world::{
|
||||
living_fluid::{LivingFluidWorld, TravelFluidTag},
|
||||
};
|
||||
impl MotionWorld<'_, '_, '_> {
|
||||
fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> {
|
||||
pub(super) fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> {
|
||||
if self.player.invulnerable || self.player.spectator {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2266,6 +2266,8 @@ pub struct Level {
|
||||
pub position: Option<[f64; 3]>,
|
||||
pub rotation: [f32; 2],
|
||||
pub health: f32,
|
||||
/// LivingEntity `AbsorptionAmount`: the golden hearts left.
|
||||
pub absorption: f32,
|
||||
pub food: i32,
|
||||
pub saturation: f32,
|
||||
/// (slot, item, count, damage): 0..36 inventory, 100..103 armor (feet..head), 150 offhand.
|
||||
@@ -2274,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).
|
||||
@@ -2288,6 +2292,8 @@ pub struct Level {
|
||||
pub dimension: String,
|
||||
/// World spawn (`level.dat` `spawn`), distinct from a bed respawn point.
|
||||
pub world_spawn: Option<[i32; 3]>,
|
||||
/// The world spawn's yaw and pitch (`setworldspawn`'s rotation).
|
||||
pub world_spawn_angle: [f32; 2],
|
||||
pub difficulty: String,
|
||||
pub hardcore: bool,
|
||||
/// `difficulty_settings.locked` (LevelData.isDifficultyLocked).
|
||||
@@ -2365,6 +2371,11 @@ impl Level {
|
||||
]
|
||||
}),
|
||||
};
|
||||
let angle = |k: &str| match data.get("spawn").and_then(|s| s.get(k)) {
|
||||
Some(Tag::Float(b)) => f32::from_bits(*b),
|
||||
_ => 0.0,
|
||||
};
|
||||
level.world_spawn_angle = [angle("yaw"), angle("pitch")];
|
||||
if let Some(d) = data.get("difficulty_settings") {
|
||||
level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into());
|
||||
level.hardcore = n(d.get("hardcore")) != 0;
|
||||
@@ -2455,6 +2466,7 @@ impl Level {
|
||||
}
|
||||
self.motion = read_doubles::<3>(p.get("Motion")).unwrap_or_default();
|
||||
self.health = f("Health").map_or(20.0, |v| v as f32);
|
||||
self.absorption = f("AbsorptionAmount").map_or(0.0, |v| v as f32);
|
||||
self.food = n("foodLevel").map_or(20, |v| v as i32);
|
||||
self.saturation = f("foodSaturationLevel").map_or(5.0, |v| v as f32);
|
||||
self.food_exhaustion = f("foodExhaustionLevel").unwrap_or(0.0) as f32;
|
||||
@@ -2465,6 +2477,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;
|
||||
@@ -2626,6 +2639,7 @@ impl Level {
|
||||
("OnGround", Tag::Byte(i8::from(self.on_ground))),
|
||||
("fall_distance", Tag::Double(self.fall_distance.to_bits())),
|
||||
("Health", Tag::Float(self.health.to_bits())),
|
||||
("AbsorptionAmount", Tag::Float(self.absorption.to_bits())),
|
||||
("foodLevel", Tag::Int(self.food)),
|
||||
("foodSaturationLevel", Tag::Float(self.saturation.to_bits())),
|
||||
(
|
||||
@@ -2686,6 +2700,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![
|
||||
@@ -2731,7 +2746,6 @@ impl Level {
|
||||
("seenCredits", Tag::Byte(0)),
|
||||
("HurtTime", Tag::Short(0)),
|
||||
("DeathTime", Tag::Short(0)),
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
@@ -2857,8 +2871,8 @@ impl Level {
|
||||
Tag::compound([
|
||||
("pos", Tag::IntArray(spawn.to_vec())),
|
||||
("dimension", string("minecraft:overworld")),
|
||||
("yaw", Tag::Float(0f32.to_bits())),
|
||||
("pitch", Tag::Float(0f32.to_bits())),
|
||||
("yaw", Tag::Float(self.world_spawn_angle[0].to_bits())),
|
||||
("pitch", Tag::Float(self.world_spawn_angle[1].to_bits())),
|
||||
]),
|
||||
),
|
||||
("difficulty_settings", difficulty),
|
||||
@@ -4114,6 +4128,7 @@ mod tests {
|
||||
position: Some([1.5, 70.0, -3.25]),
|
||||
rotation: [90.0, 10.0],
|
||||
health: 17.0,
|
||||
absorption: 5.0,
|
||||
food: 15,
|
||||
saturation: 2.5,
|
||||
inventory: vec![
|
||||
@@ -4126,6 +4141,7 @@ mod tests {
|
||||
xp_total: 30,
|
||||
dimension: "minecraft:the_nether".into(),
|
||||
world_spawn: Some([8, 64, 8]),
|
||||
world_spawn_angle: [45.0, -10.0],
|
||||
spawn: Some([20.0, 70.0, 20.0]),
|
||||
difficulty_locked: true,
|
||||
flying: true,
|
||||
@@ -4144,6 +4160,7 @@ mod tests {
|
||||
assert_eq!(back.position, Some([1.5, 70.0, -3.25]));
|
||||
assert_eq!(back.rotation, [90.0, 10.0]);
|
||||
assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5));
|
||||
assert_eq!(back.absorption, 5.0);
|
||||
let mut inv = back.inventory.clone();
|
||||
inv.sort();
|
||||
assert_eq!(
|
||||
@@ -4160,6 +4177,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(back.dimension, "minecraft:the_nether");
|
||||
assert_eq!(back.world_spawn, Some([8, 64, 8]));
|
||||
assert_eq!(back.world_spawn_angle, [45.0, -10.0]);
|
||||
assert_eq!(back.spawn, Some([20.0, 70.0, 20.0]));
|
||||
assert!(back.difficulty_locked);
|
||||
assert!(back.weather.raining);
|
||||
@@ -4178,10 +4196,13 @@ mod tests {
|
||||
let mut again = Level {
|
||||
player_extra: Some(extra),
|
||||
ender_items: ender,
|
||||
// The live amount, not the one the loaded compound held (#1307).
|
||||
absorption: 2.0,
|
||||
..back
|
||||
};
|
||||
again.write(&dir).unwrap();
|
||||
let third = Level::read(&dir).unwrap();
|
||||
assert_eq!(third.absorption, 2.0);
|
||||
assert!(matches!(
|
||||
third
|
||||
.player_extra
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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. |
|
||||
|
||||
@@ -79,6 +79,10 @@ impl Game {
|
||||
}
|
||||
fn pick(&self) -> Option<Hit> { Some(self.hit) }
|
||||
fn held(&self) -> Option<&()> { None }
|
||||
// Game::destroy_progress (hand.rs) for a harvestable block on the ground.
|
||||
fn destroy_progress(&self, _: [i32; 3]) -> f32 {
|
||||
self.res.speed / self.res.facts.hardness / 30.0
|
||||
}
|
||||
fn next_sequence(&mut self) -> i32 { self.sequence += 1; self.sequence }
|
||||
fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); }
|
||||
fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); }
|
||||
|
||||
+715
-28
@@ -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
|
||||
@@ -131,6 +138,25 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
get off by sneaking; the other side sees the animal move.
|
||||
- lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the
|
||||
sky (on its server thread the host's window is a client of it too).
|
||||
- drops: an item lies where the host, then the guest, places a block: it comes out of the block
|
||||
on the server, and both sides see it outside (#1252).
|
||||
- underwater: the host and the guest each dig dirt by hand standing under water: five times slower
|
||||
than in the air on their own client as on the server, and it breaks (#1254).
|
||||
- worldspawn: the host moves the world spawn (`setworldspawn`): the host and the guest, with no bed,
|
||||
respawn there (#1310).
|
||||
- shield: the host axes the guest's raised shield, then the guest the host's: it stays disabled
|
||||
for 5 s on that player's own cooldown, then blocks again (#1316).
|
||||
- deathmining: the host and the guest each die while breaking obsidian and let go on the death
|
||||
screen: once respawned, the obsidian stays (#1315).
|
||||
- contacts: the host and the guest each stand on magma (and sneak on it), stand on a lit campfire,
|
||||
walk against a cactus and through grown sweet berry bushes: the server hurts them, but
|
||||
not the sneaking player or young bushes (#1305, #1311, #1312, #1313).
|
||||
- absorption: the host and the guest each take Absorption II and a hit of 3: their own HUD has the
|
||||
server's golden hearts, 8 then 5 (#1306).
|
||||
- breath: the host and the guest each stay underwater for 15 s in a Respiration III helmet: their
|
||||
own bubbles follow the server's air, which the enchantment makes last (#1304).
|
||||
- lava: (--server-thread) the host and the guest each stand in a Nether lava current with Fire
|
||||
Resistance, which pushes them at the Nether's strength (#1309).
|
||||
- flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival:
|
||||
the guest, and on the server thread the host's window too, take what may fly from the
|
||||
server's abilities (ClientPacketListener.handlePlayerAbilities).
|
||||
@@ -172,7 +198,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']
|
||||
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', 'worldspawn', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -509,12 +535,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.
|
||||
@@ -542,6 +573,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)
|
||||
@@ -2296,6 +2609,380 @@ def check_flight(host, guest, out):
|
||||
return seen
|
||||
|
||||
|
||||
def check_drops(host, guest, out):
|
||||
"""A dropped item lying where a block is then placed comes out of it (#1252): the server moves
|
||||
it towards the closest open side (ItemEntity.tick's noPhysics, Entity.moveTowardsClosestSpace),
|
||||
and both sides see it outside the block. The host places one, then the guest."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
seen = {}
|
||||
for game, dz in ((host, -3), (guest, 3)):
|
||||
x, y, z = hx + 3, hy, hz + dz
|
||||
game('command', command=f'fill {x - 1} {y} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air')
|
||||
game('command', command=f'summon minecraft:item {x + 0.5} {y} {z + 0.5} '
|
||||
'{Item:{id:"minecraft:diamond",count:1},PickupDelay:32767}')
|
||||
game.wait(20)
|
||||
game('command', command=f'setblock {x} {y} {z} minecraft:stone')
|
||||
game.wait(60)
|
||||
for viewer in (host, guest):
|
||||
near = [e['pos'] for e in viewer.raw('entities', 24, 'minecraft:item')['entities']
|
||||
if abs(e['pos'][0] - x - 0.5) < 2 and abs(e['pos'][2] - z - 0.5) < 2]
|
||||
seen[f'{game.name} places, {viewer.name} sees'] = ([x, y, z], near)
|
||||
game.shot(out, 'drops')
|
||||
host('command', command='kill @e[type=minecraft:item]')
|
||||
host('command', command=f'setblock {x} {y} {z} minecraft:air')
|
||||
for name, (block, near) in seen.items():
|
||||
inside = [p for p in near if all(block[i] <= p[i] < block[i] + 1 for i in range(3))]
|
||||
assert near and not inside, f'{name}: items {near} in block {block} (all: {seen})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_underwater(host, guest, out):
|
||||
"""Digging dirt by hand underwater, standing on the bottom of a pool: five times slower than in
|
||||
the air (SUBMERGED_MINING_SPEED), on the player's own client as on the server. Halfway through
|
||||
the client is about halfway (it doesn't break the block early, which the server would put
|
||||
back), and the block breaks (#1254). The dirt is at eye height, the player's head under water.
|
||||
The host, then the guest."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
seen = {}
|
||||
for game, dz in ((host, -4), (guest, 4)):
|
||||
x, y, z = hx + 3, hy, hz + dz
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='item replace entity @s weapon.mainhand with minecraft:air')
|
||||
game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y + 3} {z + 1} minecraft:stone')
|
||||
game('command', command=f'fill {x} {y} {z} {x} {y + 2} {z} minecraft:water')
|
||||
game('command', command=f'setblock {x + 1} {y + 1} {z} minecraft:dirt')
|
||||
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
game.wait(40)
|
||||
game.raw('look-at', f'{x + 1.5:.2f}', f'{y + 1.5:.2f}', f'{z + 0.5:.2f}')
|
||||
game.wait(5)
|
||||
game.raw('mouse', 'left', 'down')
|
||||
# Dirt by hand: 15 ticks in the air, 75 under water.
|
||||
game.wait(35)
|
||||
halfway = {'mining': game('state').get('mining'), 'client': game.raw('block', x + 1, y + 1, z).get('block'),
|
||||
'server': host.raw('block', x + 1, y + 1, z).get('block'), 'y': y + 1}
|
||||
game.wait(70)
|
||||
game.raw('mouse', 'left', 'up')
|
||||
game.wait(10)
|
||||
done = host.raw('block', x + 1, y + 1, z).get('block')
|
||||
game.shot(out, 'underwater')
|
||||
seen[game.name] = {'halfway': halfway, 'done': done}
|
||||
host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y + 3} {z + 1} minecraft:air')
|
||||
host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y - 1} {z + 1} minecraft:stone')
|
||||
for name, s in seen.items():
|
||||
h = s['halfway']
|
||||
assert h['client'] == 'minecraft:dirt' == h['server'], f'{name} broke it early: {seen}'
|
||||
assert h['mining'] and h['mining']['pos'][1] == h['y'] and 0.3 < h['mining']['progress'] < 0.7, f'{name} digs at the wrong speed: {seen}'
|
||||
# Broken: air, or the pool's water flowing in.
|
||||
assert s['done'] in ('minecraft:air', 'minecraft:water'), f'{name} never broke it: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def own(game):
|
||||
"""The player's own state, as its client has it."""
|
||||
return game('state')['player']
|
||||
|
||||
|
||||
|
||||
|
||||
def check_contacts(host, guest, out):
|
||||
"""Blocks that hurt what touches them, on the server: standing on magma (but not sneaking on it)
|
||||
and on a lit campfire, walking against a cactus and through grown sweet berry bushes, for the
|
||||
host and the guest (#1305, #1311, #1312, #1313); a young bush pricks no one."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command='gamerule natural_health_regeneration false')
|
||||
seen = {}
|
||||
try:
|
||||
for game, dz in ((host, -4), (guest, 4)):
|
||||
x, y, z = hx + 2, hy, hz + dz
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='effect clear @s')
|
||||
for case, blocks, walk in (
|
||||
('magma', [(0, -1, 'minecraft:magma_block')], False),
|
||||
('sneaking', [(0, -1, 'minecraft:magma_block')], False),
|
||||
('campfire', [(0, 0, 'minecraft:campfire[lit=true]')], False),
|
||||
('cactus', [(2, -1, 'minecraft:sand'), (2, 0, 'minecraft:cactus')], True),
|
||||
('berries', [(k, -1, 'minecraft:grass_block') for k in range(1, 4)]
|
||||
+ [(k, 0, 'minecraft:sweet_berry_bush[age=3]') for k in range(1, 4)], True),
|
||||
('young', [(k, -1, 'minecraft:grass_block') for k in range(1, 4)]
|
||||
+ [(k, 0, 'minecraft:sweet_berry_bush[age=0]') for k in range(1, 4)], True)):
|
||||
game('command', command='effect give @s minecraft:instant_health 1 5 true')
|
||||
game('command', command=f'fill {x - 1} {y - 2} {z - 1} {x + 4} {y - 1} {z + 1} minecraft:stone')
|
||||
game('command', command=f'fill {x - 1} {y} {z - 1} {x + 4} {y + 2} {z + 1} minecraft:air')
|
||||
# A wall ends the walk before the player leaves the floor.
|
||||
game('command', command=f'fill {x + 5} {y - 1} {z - 1} {x + 5} {y + 2} {z + 1} minecraft:stone')
|
||||
for dx, dy, block in blocks:
|
||||
game('command', command=f'setblock {x + dx} {y + dy} {z} {block}')
|
||||
stand = 0.5 if case == 'campfire' else 0.0
|
||||
game('command', command=f'tp @s {x + 0.5} {y + stand} {z + 0.5}')
|
||||
game.raw('look-at', f'{x + 10:.2f}', f'{y + 1.6:.2f}', f'{z + 0.5:.2f}')
|
||||
game.wait(30)
|
||||
before = own(game)['health']
|
||||
keys = (['shift'] if case == 'sneaking' else []) + (['w'] if walk else [])
|
||||
for k in keys:
|
||||
game.raw('key', k, 'down')
|
||||
game.wait(60)
|
||||
for k in keys:
|
||||
game.raw('key', k, 'up')
|
||||
game.wait(10)
|
||||
seen[f'{game.name}-{case}'] = (before, own(game)['health'])
|
||||
game.shot(out, f'contacts-{case}')
|
||||
host('command', command=f'fill {x - 1} {y} {z - 1} {x + 5} {y + 2} {z + 1} minecraft:air')
|
||||
finally:
|
||||
host('command', command='gamerule natural_health_regeneration true')
|
||||
for case, (before, after) in seen.items():
|
||||
safe = case.endswith(('sneaking', 'young'))
|
||||
assert (after == before) if safe else (after < before), f'{case}: {before} -> {after} (all: {seen})'
|
||||
return seen
|
||||
|
||||
|
||||
def server_player(host, game):
|
||||
"""The player's entry on the server: the guest's in the host's `lan status`, on the server
|
||||
thread the host's too; the host's own world otherwise."""
|
||||
if game is host and not SERVER_THREAD:
|
||||
return own(host)
|
||||
name = GUEST_NAME if game is not host else host.player
|
||||
return next(g for g in host.raw('lan', 'status')['guests'] if g['name'] == name)
|
||||
|
||||
|
||||
def check_shield(host, guest, out):
|
||||
"""An axe disables a raised shield for 5 s (100 ticks), counted down once a tick on the
|
||||
server: a vindicator's axe hits each player's shield, then the cooldown left falls by about 40
|
||||
over 40 ticks (#1316)."""
|
||||
host('command', command='gamerule natural_health_regeneration false')
|
||||
rates = {}
|
||||
try:
|
||||
for game, dz in ((host, -4), (guest, 4)):
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
z += dz
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='effect give @s minecraft:resistance 60 4 true')
|
||||
game('command', command='effect give @s minecraft:instant_health 1 5 true')
|
||||
game('command', command='item replace entity @s weapon.mainhand with minecraft:air')
|
||||
game('command', command='item replace entity @s weapon.offhand with minecraft:shield')
|
||||
game('command', command=f'fill {x - 1} {y} {z - 1} {x + 4} {y + 2} {z + 1} minecraft:air')
|
||||
game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 4} {y - 1} {z + 1} minecraft:stone')
|
||||
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
game.wait(10)
|
||||
game.raw('look-at', f'{x + 2.5:.2f}', f'{y + 1.5:.2f}', f'{z + 0.5:.2f}')
|
||||
game.raw('mouse', 'right', 'down')
|
||||
game.wait(10)
|
||||
host('command', command=f'summon minecraft:vindicator {x + 2.5} {y} {z + 0.5} '
|
||||
'{PersistenceRequired:1b,Rotation:[90f,0f]}')
|
||||
host('command', command='item replace entity @e[type=minecraft:vindicator] weapon.mainhand '
|
||||
'with minecraft:iron_axe')
|
||||
first = None
|
||||
for _ in range(60):
|
||||
game.wait(5)
|
||||
first = server_player(host, game).get('shield_cooldown', 0)
|
||||
if first:
|
||||
break
|
||||
host('command', command='kill @e[type=minecraft:vindicator]')
|
||||
game.raw('mouse', 'right', 'up')
|
||||
assert first, f'{game.name}: the vindicator never disabled the shield'
|
||||
start = server_player(host, game)['shield_cooldown']
|
||||
game.wait(40)
|
||||
end = server_player(host, game)['shield_cooldown']
|
||||
rates[game.name] = {'first': first, 'start': start, 'end': end}
|
||||
game.shot(out, 'shield')
|
||||
game('command', command='item replace entity @s weapon.offhand with minecraft:air')
|
||||
game('command', command='effect clear @s')
|
||||
finally:
|
||||
host('command', command='kill @e[type=minecraft:vindicator]')
|
||||
host('command', command='gamerule natural_health_regeneration true')
|
||||
for name, r in rates.items():
|
||||
assert r['first'] <= 100, f'{name}: {rates}'
|
||||
# Once a tick: 40 down over 40 ticks, give or take the ticks the two queries straddle.
|
||||
assert 30 <= r['start'] - r['end'] <= 50, f'{name}: {rates}'
|
||||
return rates
|
||||
|
||||
|
||||
def respawn_when_ready(game):
|
||||
"""Press Respawn once the death screen lets it (DeathScreen's 20-tick delay, counted from when
|
||||
the screen opens)."""
|
||||
for _ in range(20):
|
||||
try:
|
||||
return game.raw('respawn')
|
||||
except Failed as e:
|
||||
if 'not active yet' not in str(e):
|
||||
raise
|
||||
game.wait(10)
|
||||
return game.raw('respawn')
|
||||
|
||||
|
||||
def check_world_spawn(host, guest, out):
|
||||
"""`setworldspawn` moves the world spawn: the host and the guest, with no bed of their own,
|
||||
respawn there once killed (#1310)."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
sx, sz = hx + 24, hz
|
||||
host('command', command='gamerule respawn_radius 0')
|
||||
host('command', command=f'fill {sx - 2} {hy - 1} {sz - 2} {sx + 2} {hy - 1} {sz + 2} minecraft:stone')
|
||||
host('command', command=f'fill {sx - 2} {hy} {sz - 2} {sx + 2} {hy + 3} {sz + 2} minecraft:air')
|
||||
seen = {}
|
||||
try:
|
||||
host('command', command=f'setworldspawn {sx} {hy} {sz}')
|
||||
for game in (host, guest):
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='kill @s')
|
||||
game.wait(20)
|
||||
respawn_when_ready(game)
|
||||
game.wait(60)
|
||||
seen[game.name] = [round(v, 2) for v in pos_of(game)]
|
||||
game.shot(out, 'world-spawn')
|
||||
finally:
|
||||
host('command', command=f'setworldspawn {hx} {hy} {hz}')
|
||||
host('command', command='gamerule respawn_radius 10')
|
||||
for game in (host, guest):
|
||||
game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 0.5}')
|
||||
guest.wait(20)
|
||||
for name, at in seen.items():
|
||||
assert abs(at[0] - (sx + 0.5)) < 1 and abs(at[2] - (sz + 0.5)) < 1, f'{name}: {seen}, spawn {sx} {sz}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_death_mining(host, guest, out):
|
||||
"""A player who dies while breaking obsidian, and lets go of attack on the death screen, doesn't
|
||||
break it once respawned: death forgets the digging (#1315)."""
|
||||
host('command', command='gamerule keep_inventory true')
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
seen = {}
|
||||
try:
|
||||
for game, dz in ((host, -3), (guest, 3)):
|
||||
x, y, z = hx + 2, hy, hz + dz
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='item replace entity @s weapon.mainhand with minecraft:diamond_pickaxe')
|
||||
game('command', command=f'setblock {x + 2} {y} {z} minecraft:obsidian')
|
||||
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
game.wait(10)
|
||||
game.raw('look-at', f'{x + 2.5:.2f}', f'{y + 0.5:.2f}', f'{z + 0.5:.2f}')
|
||||
game.wait(5)
|
||||
game.raw('mouse', 'left', 'down')
|
||||
game.wait(10)
|
||||
game('command', command='kill @s')
|
||||
game.wait(10)
|
||||
# The death screen lets go of the button (Minecraft.setScreen); let go again once back.
|
||||
try:
|
||||
game.raw('mouse', 'left', 'up')
|
||||
except Failed:
|
||||
pass
|
||||
game.wait(10)
|
||||
respawn_when_ready(game)
|
||||
game.wait(2)
|
||||
try:
|
||||
game.raw('mouse', 'left', 'up')
|
||||
except Failed:
|
||||
pass
|
||||
# Obsidian takes a diamond pickaxe about 190 ticks.
|
||||
game.wait(240)
|
||||
seen[game.name] = host.raw('block', x + 2, y, z).get('block')
|
||||
game.shot(out, 'death-mining')
|
||||
host('command', command=f'setblock {x + 2} {y} {z} minecraft:air')
|
||||
game('command', command='item replace entity @s weapon.mainhand with minecraft:air')
|
||||
finally:
|
||||
host('command', command='gamerule keep_inventory false')
|
||||
for name, block in seen.items():
|
||||
assert block == 'minecraft:obsidian', f'{name}: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_absorption(host, guest, out):
|
||||
"""Absorption II's golden hearts on each player's own HUD: 8 of them, and 5 once a hit of 3 took
|
||||
its share: the client shows what the server's player has (#1306)."""
|
||||
seen = {}
|
||||
for game in (host, guest):
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='effect give @s minecraft:absorption 120 1')
|
||||
game.wait(10)
|
||||
given = own(game)['absorption']
|
||||
game('command', command='damage @s 3 minecraft:generic')
|
||||
game.wait(20)
|
||||
me = own(game)
|
||||
server = server_player(host, game)
|
||||
game.shot(out, 'absorption')
|
||||
game('command', command='effect clear @s minecraft:absorption')
|
||||
seen[game.name] = {'given': given, 'left': me['absorption'], 'health': me['health'],
|
||||
'server': server.get('absorption')}
|
||||
for name, s in seen.items():
|
||||
assert s['given'] == 8.0 and s['left'] == 5.0 == s['server'] and s['health'] == 20.0, \
|
||||
f'{name}: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_breath(host, guest, out):
|
||||
"""Underwater in a Respiration III helmet for 15 s: the enchantment makes the air last on the
|
||||
server, and each player's own bubbles follow the server's air (#1304)."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
seen = {}
|
||||
for game, dz in ((host, -4), (guest, 4)):
|
||||
x, y, z = hx + 3, hy, hz + dz
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='item replace entity @s armor.head with '
|
||||
'minecraft:diamond_helmet[minecraft:enchantments={"minecraft:respiration":3}]')
|
||||
game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:stone')
|
||||
game('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} minecraft:water')
|
||||
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
host.wait(300)
|
||||
for game in (host, guest):
|
||||
game.shot(out, 'breath')
|
||||
seen[game.name] = {'own': own(game)['air'], 'server': server_player(host, game).get('air')}
|
||||
for game, dz in ((host, -4), (guest, 4)):
|
||||
x, y, z = hx + 3, hy, hz + dz
|
||||
game('command', command='item replace entity @s armor.head with minecraft:air')
|
||||
host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air')
|
||||
host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone')
|
||||
guest.wait(40)
|
||||
# 300 ticks lose about 75 of the 300 with Respiration III, all of it without.
|
||||
for name, s in seen.items():
|
||||
assert s['server'] > 150 and abs(s['own'] - s['server']) <= 10, f'{name}: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_lava(host, guest, out):
|
||||
"""(--server-thread) Standing in a settled Nether lava current with Fire Resistance: the
|
||||
Nether's FAST_LAVA pushes each player about three times as hard as the Overworld's (#1309)."""
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
seen = {}
|
||||
back = {g.name: pos_of(g) for g in (host, guest)}
|
||||
try:
|
||||
for game, z in ((host, 0), (guest, 6)):
|
||||
game('command', command=f'execute in minecraft:the_nether run tp @s 0.5 100 {z + 0.5}')
|
||||
state = wait_dimension(game, 'minecraft:the_nether', 600)
|
||||
assert state.get('dimension') == 'minecraft:the_nether', f'{game.name} is in {state.get("dimension")}'
|
||||
game.wait(40)
|
||||
# A one-wide obsidian channel along x: a source at x = -3, the current flowing east.
|
||||
game('command', command=f'fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air')
|
||||
game('command', command=f'fill -5 98 {z - 1} 6 98 {z + 1} minecraft:obsidian')
|
||||
game('command', command=f'fill -5 99 {z - 1} 6 99 {z - 1} minecraft:obsidian')
|
||||
game('command', command=f'fill -5 99 {z + 1} 6 99 {z + 1} minecraft:obsidian')
|
||||
game('command', command=f'fill -4 99 {z} -4 99 {z} minecraft:obsidian')
|
||||
game('command', command='effect give @s minecraft:fire_resistance 120 0 true')
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command=f'setblock -3 99 {z} minecraft:lava')
|
||||
host.wait(100)
|
||||
for game, z in ((host, 0), (guest, 6)):
|
||||
game('command', command=f'tp @s 0.5 99 {z + 0.5}')
|
||||
host.wait(60)
|
||||
for game, z in ((host, 0), (guest, 6)):
|
||||
v = own(game)['velocity']
|
||||
seen[game.name] = {'vx': v[0], 'level': game.raw('block', 0, 99, z).get('state')}
|
||||
game.shot(out, 'lava')
|
||||
finally:
|
||||
for game, z in ((host, 0), (guest, 6)):
|
||||
host('command', command=f'execute in minecraft:the_nether run fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air')
|
||||
x, y, zz = back[game.name]
|
||||
game('command', command='effect clear @s minecraft:fire_resistance')
|
||||
game('command', command=f'execute in minecraft:overworld run tp @s {x:.2f} {y:.2f} {zz:.2f}')
|
||||
for game in (host, guest):
|
||||
wait_dimension(game, 'minecraft:overworld', 600)
|
||||
guest.wait(40)
|
||||
# The Overworld's current settles at about 0.0047 a tick, the Nether's at about 0.014.
|
||||
for name, s in seen.items():
|
||||
assert s['vx'] > 0.009, f'{name}: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_ladder(host, guest, out):
|
||||
"""#1255: climbing down a ladder doesn't hurt where the guest lands."""
|
||||
@@ -3050,32 +3737,32 @@ def check_worn(host, guest, out):
|
||||
return taken
|
||||
|
||||
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
|
||||
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
|
||||
'respawn': check_respawn,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat,
|
||||
'machines': check_machines,
|
||||
'brewing': check_brewing,
|
||||
'loom': check_loom,
|
||||
'stonecutter': check_stonecutter,
|
||||
'grindstone': check_grindstone,
|
||||
'anvil': check_anvil,
|
||||
'smithing': check_smithing,
|
||||
'enchanting': check_enchanting,
|
||||
'beacon': check_beacon,
|
||||
'crafter': check_crafter,
|
||||
'lectern': check_lectern,
|
||||
'cartography': check_cartography,
|
||||
'hurt': check_hurt,
|
||||
'commands': check_commands,
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour,
|
||||
'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting,
|
||||
'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs,
|
||||
'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles,
|
||||
'chat': check_chat, 'machines': check_machines, 'brewing': check_brewing,
|
||||
'loom': check_loom, 'stonecutter': check_stonecutter, 'grindstone': check_grindstone,
|
||||
'anvil': check_anvil, 'smithing': check_smithing, 'enchanting': check_enchanting,
|
||||
'beacon': check_beacon, 'crafter': check_crafter, 'lectern': check_lectern,
|
||||
'cartography': check_cartography, 'hurt': check_hurt, 'commands': check_commands,
|
||||
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
|
||||
'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks,
|
||||
'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating,
|
||||
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast,
|
||||
'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}
|
||||
'effects': check_effects, 'portals': check_portals, 'distance': check_distance,
|
||||
'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push,
|
||||
'eat': check_eat, 'eating': check_eating, 'xp': check_xp,
|
||||
'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast,
|
||||
'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,
|
||||
'worldspawn': check_world_spawn, 'shield': check_shield, 'deathmining': check_death_mining,
|
||||
'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath,
|
||||
'lava': check_lava, 'levels': check_levels, 'drops': check_drops,
|
||||
'underwater': check_underwater}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
|
||||
Reference in New Issue
Block a user