Merge branch 'fix/st2-entity-hands' into fix/st2-chat

# Conflicts:
#	tools/lan_e2e.py
This commit is contained in:
Ludovic Marie
2026-10-23 09:45:17 +02:00
41 changed files with 2314 additions and 211 deletions
@@ -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>;
+73 -5
View File
@@ -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;
}
+53 -22
View File
@@ -268,6 +268,9 @@ struct Options {
/// Render into a texture instead of the window (`--offscreen`), so a
/// GPU the display cannot present from can still be benchmarked.
offscreen: bool,
/// `--width` and `--height` (vanilla's own arguments): the window's
/// starting size, 1280x720 by default.
window_size: [u32; 2],
/// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name.
server: Option<String>,
/// `--name`, `HORIZON_PLAYER_NAME` or the signed-in account's name; else
@@ -327,6 +330,7 @@ impl Options {
no_pause: false,
control: None,
offscreen: false,
window_size: [1280, 720],
spikes: std::env::var("HORIZON_SPIKES")
.ok()
.and_then(|v| v.parse().ok()),
@@ -349,7 +353,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
horizon_core::VANILLA_VERSION
);
return Ok(None);
@@ -398,6 +402,8 @@ impl Options {
"--timeout-seconds" => o.timeout = Duration::from_secs(value.parse()?),
"--smoke-report" => o.report = Some(value.into()),
"--screenshot-after" => o.screenshot_after = Some(value.parse()?),
"--width" => o.window_size[0] = value.parse::<u32>()?.max(1),
"--height" => o.window_size[1] = value.parse::<u32>()?.max(1),
"--world" => o.world = Some(value),
"--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?),
"--benchmark" => {
@@ -2110,7 +2116,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.
@@ -3603,8 +3616,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;
};
@@ -4310,6 +4321,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
@@ -9155,31 +9169,41 @@ impl Game<'_> {
} else {
pos
};
self.spawn = Some(Vec3::new(
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.6,
f64::from(head[2]) + 0.5,
));
// The bed replaces a respawn anchor.
self.respawn_config = None;
self.level.spawn = Some([
f64::from(head[0]),
f64::from(head[1]) + 1.0,
f64::from(head[2]),
]);
let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2)
+ (p.position.z - f64::from(head[2]) - 0.5).powi(2))
.sqrt();
if !night {
if dist > 3.0 {
self.message = Some((
"You can sleep only at night or during thunderstorms".into(),
"You may not rest now; the bed is too far away".into(),
Instant::now(),
));
return;
}
if dist > 3.0 {
// In reach (bedInRange), day or night: setRespawnPosition(
// RespawnConfig(the head, the player's yaw), not forced). It replaces
// an anchor or a spawnpoint; respawning checks the bed is still there
// and finds where to stand up (findRespawnAndUseSpawnBlock).
// Straw beds never set it (`straw_bed_rule`).
if self.bed_sets_spawn(state) {
self.respawn_config = Some(respawn_anchor::RespawnConfig::wrapped(
self.dim, head, p.yaw, false,
));
// The fallback becomes the world spawn: a guest's is none of its
// own, so it follows `setworldspawn`.
self.spawn = if self.lan_acting.is_some() {
None
} else {
self.level
.world_spawn
.map(|[x, y, z]| {
Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5)
})
.or(self.spawn)
};
}
if !night {
self.message = Some((
"You may not rest now; the bed is too far away".into(),
"You can sleep only at night or during thunderstorms".into(),
Instant::now(),
));
return;
@@ -9539,6 +9563,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()));
@@ -10591,6 +10616,7 @@ impl ApplicationHandler for Game<'_> {
}
// The Window constructor: created fullscreen when options.txt says so.
let fullscreen = self.settings.fullscreen;
let size = self.options.window_size.map(f64::from);
self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen);
let attributes = Window::default_attributes()
.with_title("Horizon")
@@ -10602,7 +10628,7 @@ impl ApplicationHandler for Game<'_> {
);
let window = match event_loop.create_window(
attributes
.with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0))
.with_inner_size(winit::dpi::LogicalSize::new(size[0], size[1]))
.with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))),
) {
Ok(w) => Arc::new(w),
@@ -12695,6 +12721,11 @@ impl Loading {
}
// The Window constructor: created fullscreen when options.txt says so.
let fullscreen = self.settings.fullscreen;
let size = self
.options
.as_ref()
.map_or([1280, 720], |o| o.window_size)
.map(f64::from);
self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen);
let attributes = Window::default_attributes()
.with_title("Horizon")
@@ -12706,7 +12737,7 @@ impl Loading {
);
let window = match event_loop.create_window(
attributes
.with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0))
.with_inner_size(winit::dpi::LogicalSize::new(size[0], size[1]))
.with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))),
) {
Ok(w) => Arc::new(w),
+5
View File
@@ -460,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<_>>(),
})
@@ -479,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) },
+14 -1
View File
@@ -2342,7 +2342,20 @@ 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 fallback is the world spawn (no spawnpoint of its
// own; a bed or an anchor that is gone falls back to it) 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.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()),
@@ -291,12 +291,12 @@ impl Game<'_> {
used = self.fixture_use_item(origin, op)?;
} else if let Some(op) = case.get("respawn_at") {
// ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at the origin.
let config = super::respawn_anchor::RespawnConfig {
dim: self.dim,
pos: [origin.x, origin.y, origin.z],
yaw: 0.0,
forced: op["forced"].as_bool().unwrap_or(false),
};
let config = super::respawn_anchor::RespawnConfig::wrapped(
self.dim,
[origin.x, origin.y, origin.z],
op["yaw"].as_f64().map_or(0.0, |v| v as f32),
op["forced"].as_bool().unwrap_or(false),
);
let found =
self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?;
used.push(match found {
+1
View File
@@ -2700,6 +2700,7 @@ impl Game<'_> {
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
needs_sync: false,
})
}
}
+19 -2
View File
@@ -416,7 +416,15 @@ impl Game<'_> {
f64::from(END_SPAWN[2]) + 0.5,
));
}
// Leaving the End: the respawn position (the world spawn here).
// Leaving the End: the respawn position, a bed's found once it has
// loaded (findRespawnPositionAndUseSpawnBlock, not using it up).
if let Some(c) = self.respawn_config.filter(|c| c.dim == target) {
return Some(Vec3::new(
f64::from(c.pos[0]) + 0.5,
f64::from(c.pos[1]),
f64::from(c.pos[2]) + 0.5,
));
}
let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]);
Some(Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5))
}
@@ -487,7 +495,16 @@ impl Game<'_> {
// Direction.WEST.toYRot().
return Ok((target, Some(90.0)));
}
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column.
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: where the bed or
// anchor puts the player, facing it; else onto the spawn column.
let mut target = target;
if let Some(c) = self.respawn_config.filter(|c| c.dim == self.dim) {
if let Some((at, yaw)) = self.find_respawn_and_use(c, false)? {
return Ok((at, Some(yaw)));
}
let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]);
target = Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5);
}
let y = self
.land_column(target.x.floor() as i32, target.z.floor() as i32)
.map_or(target.y, f64::from);
+10
View File
@@ -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),
@@ -760,6 +765,7 @@ impl Game<'_> {
(e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw);
e.on_ground = m.on_ground;
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
e.needs_sync = m.needs_sync;
mob_meta(m, hub, &mut e.meta);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
@@ -828,6 +834,10 @@ impl Game<'_> {
} else {
states.clear();
}
// ServerEntity.sendChanges clears needsSync once it has looked.
for m in &mut self.mobs {
m.needs_sync = false;
}
let entities = states.as_slice();
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
+93 -2
View File
@@ -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);
@@ -370,6 +380,7 @@ impl Game<'_> {
destroy_delay,
using,
use_delay,
shield_cooldown,
attack_ticks,
attack_item,
swing,
@@ -422,6 +433,7 @@ impl Game<'_> {
destroy_delay,
using,
use_delay,
shield_cooldown,
attack_ticks,
attack_item,
swing,
@@ -482,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);
@@ -1500,11 +1513,22 @@ impl Game<'_> {
// 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]
let own = host.hub.guests[i]
.respawn_elsewhere
.as_ref()
.filter(|_| server)
.map(RespawnConfig::from_saved);
let elsewhere = own.filter(|_| server);
// In the window's world a guest has no level of its own to wait in:
// its bed is resolved at once when its chunk is there, else it
// comes back on the bed.
let in_frame_bed = own.filter(|c| !server && c.dim == super::Dim::Overworld);
let spawn = in_frame_bed.map_or(spawn, |c| {
[
f64::from(c.pos[0]) + 0.5,
f64::from(c.pos[1]) + 0.6,
f64::from(c.pos[2]) + 0.5,
]
});
let level = elsewhere.map_or(super::Dim::Overworld, |c| c.dim);
let spawn = elsewhere.map_or(spawn, |c| {
[
@@ -1562,6 +1586,25 @@ impl Game<'_> {
if let Some(config) = elsewhere {
self.respawn_trip(conn, config);
}
if let Some(c) = in_frame_bed
&& self.dim == super::Dim::Overworld
&& self.world.loaded(c.pos[0], c.pos[2])
{
let found = self
.as_guest(host, conn, |g| g.resolve_server_respawn(c))
.flatten();
let world = self
.level
.world_spawn
.map_or([0.5, 80.0, 0.5], |[x, y, z]| {
[f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]
});
let at = found.map_or(world, |(at, yaw)| {
host.hub.guests[i].yaw = yaw;
[at.x, at.y, at.z]
});
host.hub.teleport(i, Some(at));
}
if away && let Err(e) = self.enter_level(Some(host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
@@ -1589,6 +1632,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;
@@ -1643,6 +1689,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;
@@ -1792,6 +1841,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;
@@ -1810,6 +1860,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 {
@@ -1835,6 +1905,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);
@@ -1995,6 +2069,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;
@@ -39,6 +39,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) ->
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
needs_sync: false,
}
}
+148 -46
View File
@@ -40,7 +40,11 @@ use horizon_protocol::{
registry::{Builtin, DimensionType, Dynamic, ceil_log2},
text::{Language, plain},
};
use horizon_world::{nbt::Tag, registry::BlockStateId};
use horizon_world::{
nbt::Tag,
registry::BlockStateId,
stepped_interpolation::{Path, PosRot, Start, SteppedInterpolation},
};
use std::{
collections::{HashMap, VecDeque},
sync::Arc,
@@ -85,6 +89,15 @@ struct Lerp {
steps: u32,
}
/// `SteppedInterpolationHandler.doInterpolate`'s `setPos` and `setRot` on a
/// mob: its yaw kept continuous (the same turn as vanilla's, without the
/// wrap that would spin it in the frame between ticks), its pitch clamped.
fn place_interpolated(m: &mut Mob, at: PosRot) {
m.position = Vec3::new(at.position[0], at.position[1], at.position[2]);
m.yaw += wrap_degrees(at.yaw - m.yaw);
m.head_pitch = (at.pitch % 360.0).clamp(-90.0, 90.0);
}
pub(super) struct Remote {
pub session: Session,
pub brand: String,
@@ -123,6 +136,8 @@ pub(super) struct Remote {
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
lerps: HashMap<i32, Lerp>,
/// Living entities' `SteppedInterpolationHandler`s.
stepped: HashMap<i32, SteppedInterpolation>,
/// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it.
head_lerps: HashMap<i32, (f32, u32)>,
/// Item entities waiting for their item data.
@@ -380,6 +395,7 @@ impl Game<'_> {
use_target: None,
entities: HashMap::new(),
lerps: HashMap::new(),
stepped: HashMap::new(),
head_lerps: HashMap::new(),
pending_items: HashMap::new(),
health: (20.0, 20, 5.0),
@@ -934,6 +950,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.entities.clear();
r.lerps.clear();
r.stepped.clear();
r.head_lerps.clear();
r.pending_items.clear();
// A new ClientLevel: a new chunk storage, centred on 0, 0.
@@ -1325,6 +1342,9 @@ impl Game<'_> {
mob.persistent = true;
self.mobs.retain(|m| m.id != id as u32);
self.mobs.push(mob);
if let Some(r) = self.remote.as_mut() {
r.stepped.remove(&id);
}
}
if let Some(r) = self.remote.as_mut() {
if kind == "minecraft:item" {
@@ -1339,23 +1359,77 @@ impl Game<'_> {
);
}
}
/// A move packet for entity `id`: to the end of `path` (None: a
/// rotation alone), turned to `rotation` if it has one. `far_snaps`:
/// an `EntityPositionSync`, which puts an entity more than 64 blocks
/// away there at once.
fn move_entity(
&mut self,
id: i32,
position: [f64; 3],
path: Option<Path>,
rotation: Option<(f32, f32)>,
on_ground: bool,
far_snaps: bool,
) {
let mob = self.mobs.iter_mut().find(|m| m.id == id as u32);
let tracked = self
.remote
.as_ref()
.and_then(|r| r.entities.get(&id))
.map(|t| t.position);
let position = path
.as_ref()
.map(Path::end)
.or(tracked)
.or_else(|| {
mob.as_ref()
.map(|m| [m.position.x, m.position.y, m.position.z])
})
.unwrap_or([0.0; 3]);
if let Some(r) = self.remote.as_mut() {
if let Some(t) = r.entities.get_mut(&id) {
t.position = position;
}
if let Some(m) = mob {
// A living entity: LivingEntity.createInterpolationHandler's
// SteppedInterpolationHandler, over its type's update interval.
let entity = PosRot {
position: [m.position.x, m.position.y, m.position.z],
yaw: m.yaw,
pitch: m.head_pitch,
};
let far = far_snaps && {
let d = [0, 1, 2].map(|i| position[i] - entity.position[i]);
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 4096.0
};
let handler = r.stepped.entry(id).or_insert_with(|| {
let interval = horizon_client::lan::tracking::settings(&m.kind.id).1;
SteppedInterpolation::new(interval as i32)
});
let snap = if far {
handler.cancel();
let (yaw, pitch) = rotation.unwrap_or((m.yaw, m.head_pitch));
Some(PosRot {
position,
yaw,
pitch,
})
} else {
match handler.interpolate_to(entity, path, rotation) {
Start::Snap(at) => Some(at),
Start::Interpolating | Start::Unchanged => None,
}
};
if let Some(at) = snap {
place_interpolated(m, at);
m.previous = m.position;
}
m.on_ground = on_ground;
return;
}
// AbstractInterpolationHandler.interpolateTo: without a rotation,
// the one it was heading for (or has).
let rotation = rotation
.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation))
.or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch)));
// the one it was heading for.
let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation));
r.lerps.insert(
id,
Lerp {
@@ -1368,9 +1442,6 @@ impl Game<'_> {
*p = position;
}
}
if let Some(m) = mob {
m.on_ground = on_ground;
}
self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground);
self.turn_remote_projectile(id, rotation);
}
@@ -1387,6 +1458,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.entities.remove(&id);
r.lerps.remove(&id);
r.stepped.remove(&id);
r.head_lerps.remove(&id);
r.pending_items.remove(&id);
}
@@ -1746,17 +1818,36 @@ impl Game<'_> {
.and_then(|r| r.entities.get(&m.id))
.map(|t| t.position);
let Some(base) = base else { return Ok(()) };
let position = m.delta.as_ref().map_or(base, |d| d.end(base));
// VecDeltaCodec.decode: each step's position from the last.
let path = m.delta.as_ref().map(|d| match d {
play::VecDelta::Linear(_) => Path::Linear(d.end(base)),
play::VecDelta::Stepped(steps) => {
let mut at = base;
Path::Stepped(
steps
.iter()
.map(|(delta, ticks)| {
at = play::VecDelta::apply(at, *delta);
(at, *ticks)
})
.collect(),
)
}
});
let rotation = m.rotation.map(|(y, x)| {
(
horizon_protocol::buf::unpack_degrees(y),
horizon_protocol::buf::unpack_degrees(x),
)
});
self.move_entity(m.id, position, rotation, m.on_ground);
self.move_entity(m.id, path, rotation, m.on_ground, false);
}
C::EntityPositionSync(p) => {
self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground)
let path = match p.path {
play::PositionPath::Linear(at) => Path::Linear(at),
play::PositionPath::Stepped(steps) => Path::Stepped(steps),
};
self.move_entity(p.id, Some(path), Some((p.yaw, p.pitch)), p.on_ground, true)
}
C::TeleportEntity(p) => {
let base = self
@@ -1776,7 +1867,13 @@ impl Game<'_> {
rel(play::relative::Y, 1),
rel(play::relative::Z, 2),
];
self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground);
self.move_entity(
p.id,
Some(Path::Linear(position)),
Some((p.yaw, p.pitch)),
p.on_ground,
false,
);
}
C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers),
C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw),
@@ -1870,11 +1967,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);
}
}
_ => {}
}
}
}
@@ -2996,6 +3109,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 {
@@ -3148,6 +3268,7 @@ impl Game<'_> {
return;
};
let mut lerps = std::mem::take(&mut r.lerps);
let stepped = &mut r.stepped;
let head_lerps = &mut r.head_lerps;
let players = &r.level_players;
let mut using = Vec::new();
@@ -3178,22 +3299,12 @@ impl Game<'_> {
// LivingEntity.updateSwingTime.
m.anim.attack_anim_o = m.anim.attack_anim;
horizon_client::mobs::ai::tick_swing(m);
// Entity.commonTick: LinearInterpolationHandler.interpolate.
if let Some(l) = lerps.get_mut(&(m.id as i32))
&& l.steps > 0
// Entity.tick: the SteppedInterpolationHandler's step.
if let Some(at) = stepped
.get_mut(&(m.id as i32))
.and_then(|h| h.interpolate())
{
let n = f64::from(l.steps);
m.position = Vec3::new(
m.position.x + (l.target[0] - m.position.x) / n,
m.position.y + (l.target[1] - m.position.y) / n,
m.position.z + (l.target[2] - m.position.z) / n,
);
if let Some((yaw, pitch)) = l.rotation {
let alpha = 1.0 / l.steps as f32;
m.yaw += wrap_degrees(yaw - m.yaw) * alpha;
m.head_pitch += (pitch - m.head_pitch) * alpha;
}
l.steps -= 1;
place_interpolated(m, at);
}
// LivingEntity.aiStep: the head's own interpolation.
if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32))
@@ -3468,22 +3579,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
@@ -222,6 +222,7 @@ impl Game<'_> {
hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope);
self.screen_fx.build(&ScreenInputs {
sprites: &self.gui.atlas.sprites,
flags: &self.gui.atlas.flags,
aspect: size[0] as f32 / size[1].max(1) as f32,
partial,
block_overlay,
@@ -36,6 +36,15 @@ pub(super) struct RespawnConfig {
pub(super) type SavedRespawn = (String, [i32; 3], f32, bool);
impl RespawnConfig {
/// `RespawnData.of`: the yaw wrapped to [-180, 180).
pub(super) fn wrapped(dim: Dim, pos: [i32; 3], yaw: f32, forced: bool) -> Self {
Self {
dim,
pos,
yaw: wrap_degrees(f64::from(yaw)) as f32,
forced,
}
}
pub(super) fn from_saved((dim, pos, yaw, forced): &SavedRespawn) -> Self {
Self {
dim: Dim::from_id(dim),
@@ -80,7 +89,7 @@ pub(super) enum AnchorUse {
}
impl Game<'_> {
fn is_anchor(&self, state: BlockStateId) -> bool {
pub(super) fn is_anchor(&self, state: BlockStateId) -> bool {
&*self.res.facts().get(state).name == "minecraft:respawn_anchor"
}
fn anchor_charges(&self, state: BlockStateId) -> i32 {
@@ -456,9 +465,87 @@ impl Game<'_> {
}
None
}
/// `AbstractBedBlock.findStandUpPosition` for a bed whose head is at
/// `pos`, facing `forward`, set from `yaw`: beside the bed on the side
/// the player faced away from, around it, then on it; a safe spot
/// first, else any spot (a bunk bed: around it, a block lower, then on
/// it).
pub(super) fn bed_stand_up(&self, pos: [i32; 3], forward: [i32; 3], yaw: f32) -> Option<Vec3> {
// Direction.getClockWise.
let right = [-forward[2], 0, forward[0]];
// Direction.isFacingAngle.
let radians = yaw * 0.017_453_292;
let (dx, dz) = (
-horizon_core::geometry::trig::sin(f64::from(radians)),
horizon_core::geometry::trig::cos(f64::from(radians)),
);
let facing = right[0] as f32 * dx + right[2] as f32 * dz > 0.0;
let side = if facing {
[-right[0], 0, -right[2]]
} else {
right
};
let (f, s) = ([forward[0], forward[2]], [side[0], side[2]]);
// bedSurroundStandUpOffsets and bedAboveStandUpOffsets.
let surround = [
[s[0], s[1]],
[s[0] - f[0], s[1] - f[1]],
[s[0] - f[0] * 2, s[1] - f[1] * 2],
[-f[0] * 2, -f[1] * 2],
[-s[0] - f[0] * 2, -s[1] - f[1] * 2],
[-s[0] - f[0], -s[1] - f[1]],
[-s[0], -s[1]],
[-s[0] + f[0], -s[1] + f[1]],
[f[0], f[1]],
[s[0] + f[0], s[1] + f[1]],
];
let above = [[0, 0], [-f[0], -f[1]]];
let at = |base: [i32; 3], offsets: &[[i32; 2]], check: bool| {
offsets.iter().find_map(|o| {
self.safe_dismount_location([base[0] + o[0], base[1], base[2] + o[1]], check)
})
};
let below = [pos[0], pos[1] - 1, pos[2]];
// isBunkBed: a bed below.
if self.is_bed(self.world.block(below[0], below[1], below[2])) {
return at(pos, &surround, true)
.or_else(|| at(below, &surround, true))
.or_else(|| at(pos, &above, true))
.or_else(|| at(pos, &surround, false))
.or_else(|| at(below, &surround, false))
.or_else(|| at(pos, &above, false));
}
let all: Vec<[i32; 2]> = surround.into_iter().chain(above).collect();
at(pos, &all, true).or_else(|| at(pos, &all, false))
}
pub(super) fn is_bed(&self, state: BlockStateId) -> bool {
self.res.facts().get(state).name.ends_with("_bed")
}
/// The bed's `facing`, as a step.
fn bed_forward(&self, state: BlockStateId) -> [i32; 3] {
let facing = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing").cloned());
match facing.as_deref() {
Some("south") => [0, 0, 1],
Some("west") => [-1, 0, 0],
Some("east") => [1, 0, 0],
_ => [0, 0, -1],
}
}
/// `BedRule.canSetSpawn` of the bed's rule attribute (`bed_rule`,
/// `straw_bed_rule`): only the Overworld's beds set the spawn, straw
/// beds never.
pub(super) fn bed_sets_spawn(&self, state: BlockStateId) -> bool {
self.dim == Dim::Overworld && &*self.res.facts().get(state).name != "minecraft:straw_bed"
}
/// `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.
/// dimension: the position and yaw, using an anchor's charge; a bed's
/// stand-up spot. A forced point (`spawnpoint`) that is no anchor or bed
/// holds if a player fits in it; anything else is gone.
pub(super) fn find_respawn_and_use(
&mut self,
c: RespawnConfig,
@@ -469,6 +556,12 @@ impl Game<'_> {
&& (c.forced || self.anchor_charges(state) > 0)
&& self.anchor_works())
{
// A bed where its bed rule lets it set the spawn.
if self.is_bed(state) && self.bed_sets_spawn(state) {
let facing = self.bed_forward(state);
let stand = self.bed_stand_up(c.pos, facing, c.yaw);
return Ok(stand.map(|p| (p, look_at_yaw(p, c.pos))));
}
let [x, y, z] = c.pos;
let free = c.forced
&& !self.is_anchor(state)
+21 -10
View File
@@ -193,11 +193,16 @@ impl Game<'_> {
_ => 1.0,
};
self.end_portal_travel = end;
let scaled = self.end_destination(target).unwrap_or(Vec3::new(
from.x * scale,
from.y,
from.z * scale,
));
// Leaving the End: the player's own respawn point.
let own = if end {
self.as_guest(host, conn, |g| g.end_destination(target))
.flatten()
} else {
None
};
let scaled = own
.or_else(|| self.end_destination(target))
.unwrap_or(Vec3::new(from.x * scale, from.y, from.z * scale));
self.end_portal_travel = false;
if let Err(e) = self.enter_level(Some(host), target) {
log::error!("could not open {}: {e}", target.id());
@@ -244,13 +249,15 @@ impl Game<'_> {
}
/// `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
/// in the level in place: where it stands up, facing the anchor (with
/// the deplete sound) or the bed; else the point is forgotten
/// (`block.minecraft.spawn.not_valid`).
fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> {
pub(super) fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> {
let [x, y, z] = config.pos;
let anchor = self.is_anchor(self.world.block(x, y, z));
match self.find_respawn_and_use(config, true) {
Ok(Some((at, yaw))) => {
if !config.forced {
if !config.forced && anchor {
let [x, y, z] = config.pos.map(f64::from);
self.audio.play(
"minecraft:block.respawn_anchor.deplete",
@@ -357,7 +364,11 @@ impl Game<'_> {
}
}
} else if trip.end {
match self.end_arrival(trip.target) {
let arrival = match self.as_guest(host, trip.conn, |g| g.end_arrival(trip.target)) {
Some(arrival) => arrival,
None => self.end_arrival(trip.target),
};
match arrival {
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
Err(e) => {
log::error!("End arrival: {e}");
+53 -37
View File
@@ -357,8 +357,9 @@ pub struct Renderer {
border_group: wgpu::BindGroup,
border_uniform: wgpu::Buffer,
border_vertices: wgpu::Buffer,
/// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines.
screen_pipelines: [wgpu::RenderPipeline; 2],
/// Screen effects: alpha-blended, then vignette (`dst * (1 - src)`)
/// pipelines, each for every sampling (index `blend * 4 + sampling`).
screen_pipelines: [wgpu::RenderPipeline; 8],
screen_buffer: wgpu::Buffer,
screen_capacity: u64,
entity_group: wgpu::BindGroup,
@@ -2001,37 +2002,52 @@ impl Renderer {
operation: wgpu::BlendOperation::Add,
},
};
let screen_pipelines =
[("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Screen effects"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &screen_shader,
entry_point: Some("vs_screen"),
compilation_options: Default::default(),
buffers: &screen_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &screen_shader,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
});
// One per blend and `.png.mcmeta` sampling (screen_effects::SAMPLE_*):
// the shader is specialised, so a pixel pays for none of the others.
let screen_pipelines: [wgpu::RenderPipeline; 8] = std::array::from_fn(|i| {
let (entry, blend) = if i & 4 == 0 {
("fs_screen", alpha_blend)
} else {
("fs_vignette", vignette_blend)
};
let on = |bit: u32| f64::from(u8::from(i as u32 & bit != 0));
let constants = [
("BLUR", on(crate::screen_effects::SAMPLE_BLUR)),
("CLAMP", on(crate::screen_effects::SAMPLE_CLAMP)),
];
let compilation_options = wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
};
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Screen effects"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &screen_shader,
entry_point: Some("vs_screen"),
compilation_options: compilation_options.clone(),
buffers: &screen_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &screen_shader,
entry_point: Some(entry),
compilation_options,
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
});
let screen_capacity = 64;
let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Screen effect vertices"),
@@ -3911,11 +3927,11 @@ impl Renderer {
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.screen_buffer.slice(..));
for (i, quad) in frame.screen.iter().enumerate() {
let pipeline = match quad.blend {
crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0],
crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1],
let blend = match quad.blend {
crate::screen_effects::Blend::Alpha => 0,
crate::screen_effects::Blend::Vignette => 4,
};
pass.set_pipeline(pipeline);
pass.set_pipeline(&self.screen_pipelines[blend + (quad.sampling & 3) as usize]);
pass.draw_indexed(0..6, (i * 4) as i32, 0..1);
}
}
+92 -5
View File
@@ -18,11 +18,35 @@ pub struct Rect {
pub w: u32,
pub h: u32,
}
/// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a
/// standalone texture (`ReloadableTexture.setSampler`: linear rather than
/// nearest filtering, clamp-to-edge rather than repeat addressing).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextureFlags {
pub blur: bool,
pub clamp: bool,
}
impl TextureFlags {
/// The `texture` section of a `.png.mcmeta` file, if it sets either flag.
pub fn from_mcmeta(json: &str) -> Option<Self> {
let meta: serde_json::Value = serde_json::from_str(json).ok()?;
let section = meta.get("texture")?;
let flag = |key| section.get(key).and_then(serde_json::Value::as_bool) == Some(true);
let flags = Self {
blur: flag("blur"),
clamp: flag("clamp"),
};
(flags != Self::default()).then_some(flags)
}
}
pub struct HudAtlas {
pub pixels: Vec<u8>,
pub width: u32,
pub height: u32,
pub sprites: HashMap<String, Rect>,
/// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others
/// sample as vanilla's defaults (nearest, repeat).
pub flags: HashMap<String, TextureFlags>,
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>,
/// The default font (bitmap sheets in this atlas, unifont rasterized on demand).
pub font: crate::font::Font,
@@ -80,6 +104,20 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
}
/// A packed atlas image: sprite name, size and RGBA pixels.
type PackedImage = (String, u32, u32, Vec<u8>);
/// `image` inside a one-texel border copied from its opposite edges, the
/// texels repeat addressing reads past each edge.
fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage {
let (bw, bh) = (w + 2, h + 2);
let mut out = Vec::with_capacity((bw * bh * 4) as usize);
for y in 0..bh {
let row = (y + h - 1) % h;
for x in 0..bw {
let at = ((row * w + (x + w - 1) % w) * 4) as usize;
out.extend_from_slice(&data[at..at + 4]);
}
}
(name.clone(), bw, bh, out)
}
/// Sprites the atlas definitions (`atlases/*.json`) add beyond the texture
/// files already packed: generated ones (`paletted_permutations` such as the
/// armour trim sprites, `unstitch` regions) and files listed under another id.
@@ -243,7 +281,7 @@ impl HudAtlas {
let s = p.to_string_lossy();
!s.contains("title/background") && !s.contains("realms") && !s.contains("presets")
});
let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec<u8>)> {
let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option<TextureFlags>)> {
let name = path
.strip_prefix(&textures)
.ok()?
@@ -258,11 +296,15 @@ impl HudAtlas {
} else {
pixels
};
(w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels))
let flags = fs::read_to_string(path.with_extension("png.mcmeta"))
.ok()
.and_then(|json| TextureFlags::from_mcmeta(&json));
(w <= 1024 && (h <= 512 || name.starts_with("font/")))
.then_some(((name, w, h, pixels), flags))
};
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
let chunk = files.len().div_ceil(threads).max(1);
let mut images: Vec<_> = std::thread::scope(|scope| {
let decoded: Vec<_> = std::thread::scope(|scope| {
let handles: Vec<_> = files
.chunks(chunk)
.map(|part| {
@@ -274,6 +316,14 @@ impl HudAtlas {
.flat_map(|h| h.join().unwrap_or_default())
.collect()
});
let mut flags = HashMap::new();
let mut images: Vec<PackedImage> = Vec::with_capacity(decoded.len());
for (image, image_flags) in decoded {
if let Some(f) = image_flags {
flags.insert(image.0.clone(), f);
}
images.push(image);
}
if full {
images.extend(atlas_sprites(root, &images));
}
@@ -290,6 +340,16 @@ impl HudAtlas {
if full {
Self::slots(&mut images, crate::trims::slot_size(root));
}
// Blurred sprites are sampled linearly in the atlas (screen.wgsl): a
// border wrapped from their own edges keeps the filter off their
// neighbours, as repeat addressing of their own texture would.
let mut bordered = std::collections::HashSet::new();
for image in &mut images {
if flags.get(&image.0).is_some_and(|f: &TextureFlags| f.blur) {
*image = wrap_border(image);
bordered.insert(image.0.clone());
}
}
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
let width = 4096u32;
let mut placements = Vec::with_capacity(images.len());
@@ -314,6 +374,8 @@ impl HudAtlas {
let dst = (((py + row) * width + px) * 4) as usize;
pixels[dst..dst + (w * 4) as usize].copy_from_slice(src);
}
let b = u32::from(bordered.contains(name));
let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b);
sprites.insert(
name.clone(),
Rect {
@@ -321,8 +383,8 @@ impl HudAtlas {
v0: py as f32 / height as f32,
u1: (px + w) as f32 / width as f32,
v1: (py + h) as f32 / height as f32,
w: *w,
h: *h,
w,
h,
},
);
}
@@ -369,6 +431,7 @@ impl HudAtlas {
width,
height,
sprites,
flags,
fire_animations,
font,
white,
@@ -1277,6 +1340,30 @@ impl HudRenderer {
mod tests {
use super::*;
#[test]
fn a_wrapped_border_repeats_the_opposite_edges() {
// 2x2 texels a b / c d, one byte each in red.
let image = (
"x".to_owned(),
2,
2,
[1u8, 2, 3, 4]
.iter()
.flat_map(|&v| [v, 0, 0, 255])
.collect(),
);
let (_, w, h, data) = wrap_border(&image);
assert_eq!((w, h), (4, 4));
let red: Vec<u8> = data.chunks(4).map(|t| t[0]).collect();
#[rustfmt::skip]
assert_eq!(red, [
4, 3, 4, 3,
2, 1, 2, 1,
4, 3, 4, 3,
2, 1, 2, 1,
]);
}
/// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
fn two_glyph_font(name: &str) -> std::path::PathBuf {
let root =
+37 -2
View File
@@ -59,6 +59,8 @@ pub struct EntityState {
/// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks
/// touching a block): moves are sent as full position syncs.
pub precise: bool,
/// `Entity.needsSync`: send its changes this tick, due or not.
pub needs_sync: bool,
}
impl EntityState {
@@ -79,6 +81,7 @@ impl EntityState {
self.equipment.clear();
self.attributes.clear();
self.precise = false;
self.needs_sync = false;
}
}
@@ -322,7 +325,7 @@ impl ServerEntity {
// SynchedEntityData.isDirty: once for every client.
let dirty = e.meta != self.meta;
let due = self.interval != 0 && self.tick.is_multiple_of(self.interval);
if due || dirty {
if due || dirty || e.needs_sync {
let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw));
let turned = |a: i8, b: i8| (i32::from(a) - i32::from(b)).abs() >= 1;
let rotate = self.arrow
@@ -398,7 +401,7 @@ impl ServerEntity {
} else {
None
};
if self.track_deltas {
if self.track_deltas || e.needs_sync {
let diff: f64 = (0..3)
.map(|k| (e.velocity[k] - self.velocity[k]).powi(2))
.sum();
@@ -859,6 +862,7 @@ mod tests {
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
needs_sync: false,
}
}
@@ -922,6 +926,37 @@ mod tests {
assert!(matches!(jump[0], play::Clientbound::EntityPositionSync(_)));
}
#[test]
fn a_knocked_back_mob_is_sent_at_once() {
let mut s = added(&state(0.0));
changes(&mut s, &state(0.0));
// Not due (tick 1 of 3), but LivingEntity.knockback set needsSync:
// its move and its new motion go out now.
let mut knocked = state(0.3);
knocked.velocity = [0.2, 0.3, 0.0];
knocked.needs_sync = true;
let out = changes(&mut s, &knocked);
assert!(
matches!(
out[..],
[
play::Clientbound::SetEntityMotion(_),
play::Clientbound::MoveEntityPos(_)
]
),
"{out:?}"
);
// Then every third tick again.
assert!(changes(&mut s, &state(0.5)).is_empty());
assert!(matches!(
changes(&mut s, &state(0.6))[..],
[
play::Clientbound::SetEntityMotion(_),
play::Clientbound::MoveEntityPos(_)
]
));
}
#[test]
fn fireballs_bundle_their_motion_with_their_power() {
let mut e = state(0.0);
+9
View File
@@ -153,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,
@@ -172,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).
@@ -285,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,
@@ -297,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,
+25 -1
View File
@@ -1562,6 +1562,7 @@ impl Hub {
equipment,
attributes,
precise: false,
needs_sync: false,
}
}
@@ -1770,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];
@@ -2480,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,
+13 -1
View File
@@ -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,12 @@ 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();
@@ -124,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;
+7
View File
@@ -792,6 +792,9 @@ pub struct Mob {
pub on_ground: bool,
pub horizontal_collision: bool,
pub vertical_collision_below: bool,
/// `Entity.needsSync`: knocked back, pushed or jumped since its server
/// last sent it, so the next update goes out at once.
pub needs_sync: bool,
pub health: f32,
pub hurt_time: i32,
pub invulnerable: i32,
@@ -1361,8 +1364,10 @@ impl PendingPushes {
}
/// Adds the pending pushes aimed at `m` to its velocity, in push order.
pub fn apply_mob_pushes(m: &mut Mob, pending: &mut PendingPushes) {
// Entity.push(x, y, z) sets needsSync.
let mut add = |v: Vec3| {
m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z);
m.needs_sync = true;
};
if !pending.list.is_empty() {
pending.list.retain(|(id, v)| {
@@ -1529,6 +1534,7 @@ impl Mob {
on_ground: false,
horizontal_collision: false,
vertical_collision_below: false,
needs_sync: false,
hurt_time: 0,
invulnerable: 0,
death_time: 0,
@@ -1769,6 +1775,7 @@ impl Mob {
if power <= 0.0 {
return;
}
self.needs_sync = true;
while xd * xd + zd * zd < f64::from(1.0e-5_f32) {
xd = (self.random.next_double() - self.random.next_double()) * 0.01;
zd = (self.random.next_double() - self.random.next_double()) * 0.01;
+3
View File
@@ -832,6 +832,9 @@ impl Mob {
};
}
pub fn jump_from_ground(&mut self, w: &MobWorld) {
// LivingEntity.jumpFromGround (and the rabbit's and cubes' own,
// which call it or do the same): needsSync.
self.needs_sync = true;
if self.species() == super::Species::Rabbit {
super::rabbit::jump(self, w);
return;
+72 -3
View File
@@ -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(());
}
+33 -8
View File
@@ -2258,14 +2258,18 @@ pub struct Level {
pub game_mode: i32,
pub time: i64,
pub day_time: i64,
/// The player's respawn point (bed, or the world spawn).
/// Where the player respawns when it has no bed or anchor: its forced
/// Overworld point (`spawnpoint`), or the world spawn.
pub spawn: Option<[f64; 3]>,
/// A respawn point in another dimension than the Overworld (a respawn
/// anchor): dimension, block, yaw and `forced`.
/// A respawn point resolved through its block when the player respawns
/// (a bed, a respawn anchor, a forced point outside the Overworld):
/// dimension, block, yaw and `forced`.
pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>,
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.
@@ -2290,6 +2294,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).
@@ -2367,6 +2373,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;
@@ -2457,6 +2468,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;
@@ -2485,14 +2497,17 @@ impl Level {
{
let dimension =
text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into());
if dimension == "minecraft:overworld" {
let forced = number(respawn.get("forced")).is_some_and(|v| v != 0);
// A forced point in the Overworld (`spawnpoint`) is where the
// player respawns; anything else (a bed, an anchor) is resolved
// through its block then.
if dimension == "minecraft:overworld" && forced {
self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]);
} else {
let yaw = match respawn.get("yaw") {
Some(Tag::Float(b)) => f32::from_bits(*b),
_ => 0.0,
};
let forced = number(respawn.get("forced")).is_some_and(|v| v != 0);
self.respawn_elsewhere = Some((dimension, [pos[0], pos[1], pos[2]], yaw, forced));
}
}
@@ -2629,6 +2644,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())),
(
@@ -2708,6 +2724,8 @@ impl Level {
s[1].floor() as i32,
s[2].floor() as i32,
];
// A point of the player's own in the Overworld other than a bed
// (`respawn_elsewhere`): `spawnpoint`'s, forced.
if Some(block) != self.world_spawn {
entries.push((
"respawn",
@@ -2716,6 +2734,7 @@ impl Level {
("pos", Tag::IntArray(block.to_vec())),
("yaw", Tag::Float(0f32.to_bits())),
("pitch", Tag::Float(0f32.to_bits())),
("forced", Tag::Byte(1)),
]),
));
}
@@ -2735,7 +2754,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);
@@ -2861,8 +2879,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),
@@ -4118,6 +4136,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![
@@ -4130,6 +4149,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,
@@ -4148,6 +4168,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!(
@@ -4164,6 +4185,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);
@@ -4182,10 +4204,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
+31 -6
View File
@@ -1,12 +1,25 @@
// Full-screen camera effects (screen_effects.rs): clip-space quads sampling
// the shared 2D atlas with repeat inside each sprite rectangle.
// Full-screen camera effects (screen_effects.rs): clip-space quads reading
// one sprite rectangle of the shared 2D atlas as if it were its own texture,
// with the sampler vanilla gives it (ReloadableTexture.setSampler: linear
// when `blur`, clamp-to-edge when `clamp`, else nearest and repeat).
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;
// The block sprites' sampler (nearest), and the entity group's lightmap
// sampler (linear) for `blur`. A blurred sprite has a one-texel border in the
// atlas, wrapped as repeat reads it (hud.rs), so the hardware's bilinear
// sample is GL_LINEAR with repeat; clamp-to-edge keeps the sample point half
// a texel inside. Each sampling has its own pipeline (gfx.rs), so a pixel
// costs what it did with nearest and repeat only: one sample.
@group(0) @binding(2) var nearest_sampler: sampler;
@group(0) @binding(4) var linear_sampler: sampler;
override BLUR: bool = false;
override CLAMP: bool = false;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) @interpolate(flat) rect: vec4<f32>,
@location(2) color: vec4<f32>,
// With clamp-to-edge, the sprite's first and last texel centres.
@location(3) @interpolate(flat) edges: vec4<f32>,
}
@vertex fn vs_screen(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>,
@location(2) rect: vec4<f32>, @location(3) color: vec4<f32>) -> Out {
@@ -15,12 +28,24 @@ struct Out {
out.uv = uv;
out.rect = rect;
out.color = color;
let half = 0.5 / vec2<f32>(textureDimensions(atlas));
out.edges = vec4(rect.xy + half, rect.zw - half);
return out;
}
fn sample(in: Out) -> vec4<f32> {
let f = fract(in.uv);
let uv = in.rect.xy + f * (in.rect.zw - in.rect.xy);
return textureSampleLevel(atlas, atlas_sampler, uv, 0.0) * in.color;
var f = in.uv;
if !CLAMP {
// Repeat: one period of the sprite.
f = fract(f);
}
var uv = in.rect.xy + f * (in.rect.zw - in.rect.xy);
if CLAMP {
uv = clamp(uv, in.edges.xy, in.edges.zw);
}
if BLUR {
return textureSampleLevel(atlas, linear_sampler, uv, 0.0) * in.color;
}
return textureSampleLevel(atlas, nearest_sampler, uv, 0.0) * in.color;
}
@fragment fn fs_screen(in: Out) -> @location(0) vec4<f32> {
let c = sample(in);
+114 -5
View File
@@ -4,7 +4,10 @@
//! `hud_overlays::camera_overlays` (vignette, pumpkin blur, powder-snow
//! outline, nether portal swirl). Positions are clip-space quads; textures
//! come from the shared 2D atlas and may repeat.
use crate::{hud::Rect, hud_layout::GuiDraw};
use crate::{
hud::{Rect, TextureFlags},
hud_layout::GuiDraw,
};
use std::collections::HashMap;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -25,15 +28,28 @@ pub struct ScreenVertex {
pub rect: [f32; 4],
pub color: [f32; 4],
}
/// Linear filtering (`TextureMetadataSection.blur`), else nearest.
pub const SAMPLE_BLUR: u32 = 1;
/// Clamp-to-edge addressing (`TextureMetadataSection.clamp`), else repeat.
pub const SAMPLE_CLAMP: u32 = 2;
/// The sampling bits of a standalone texture's flags.
pub fn sampling(flags: TextureFlags) -> u32 {
let bit = |on: bool, bit: u32| if on { bit } else { 0 };
bit(flags.blur, SAMPLE_BLUR) | bit(flags.clamp, SAMPLE_CLAMP)
}
#[derive(Clone, Debug)]
pub struct ScreenQuad {
pub vertices: [ScreenVertex; 4],
pub blend: Blend,
/// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`].
pub sampling: u32,
}
/// What the camera sees this frame.
pub struct ScreenInputs<'a> {
pub sprites: &'a HashMap<String, Rect>,
/// `.png.mcmeta` sampling of the standalone textures among `sprites`.
pub flags: &'a HashMap<String, TextureFlags>,
pub aspect: f32,
pub partial: f32,
/// Particle sprite of the view-blocking block around the eye.
@@ -92,12 +108,17 @@ impl ScreenEffects {
pub fn build(&self, input: &ScreenInputs) -> Vec<ScreenQuad> {
let mut out = Vec::new();
let sprite = |name: &str| input.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
// Standalone textures (`ReloadableTexture.setSampler`) follow their
// metadata; atlas sprites (block overlay, fire, portal) sample
// nearest with repeat.
let texture_sampling = |name: &str| input.flags.get(name).copied().map_or(0, sampling);
let scale = hand_scale(input.aspect);
// Screen-effect quads live at view depth 0.5 in the hand projection.
let hand_quad = |corners: [[f32; 2]; 4],
uv: [[f32; 2]; 4],
rect: [f32; 4],
color: [f32; 4]| ScreenQuad {
color: [f32; 4],
sampling: u32| ScreenQuad {
vertices: std::array::from_fn(|i| ScreenVertex {
pos: [corners[i][0] * scale[0], corners[i][1] * scale[1]],
uv: uv[i],
@@ -105,6 +126,7 @@ impl ScreenEffects {
color,
}),
blend: Blend::Alpha,
sampling,
};
let full = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]];
// ScreenEffectRenderer.submitBlockSprite: u1/v1 at (-1, -1), colour 0xFF191919.
@@ -117,6 +139,7 @@ impl ScreenEffects {
[[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]],
rect,
[c, c, c, 1.0],
0,
));
}
if let Some((brightness, yaw, pitch)) = input.water
@@ -129,6 +152,7 @@ impl ScreenEffects {
uv,
rect,
[brightness, brightness, brightness, 0.1],
texture_sampling("misc/underwater"),
));
}
if input.on_fire
@@ -150,11 +174,12 @@ impl ScreenEffects {
[[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]],
rect,
[1.0, 1.0, 1.0, alpha],
0,
));
}
}
// Hud camera overlays: GUI-space full-screen blits (v grows downwards).
let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend| ScreenQuad {
let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend, sampling: u32| ScreenQuad {
vertices: std::array::from_fn(|i| {
let p = [[-1.0f32, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]][i];
ScreenVertex {
@@ -165,6 +190,7 @@ impl ScreenEffects {
}
}),
blend,
sampling,
};
let rgba = |c: u32| {
let [a, r, g, b] = c.to_be_bytes();
@@ -187,8 +213,14 @@ impl ScreenEffects {
} else {
Blend::Alpha
};
// The vignette darkens by texture × colour: black (in
// daylight its brightness fades to 0 within half a
// minute) leaves every pixel as it was.
if blend == Blend::Vignette && color & 0x00ff_ffff == 0 {
continue;
}
if let Some(rect) = sprite(texture) {
out.push(gui(rect, rgba(*color), blend));
out.push(gui(rect, rgba(*color), blend, texture_sampling(texture)));
}
}
GuiDraw::AtlasSprite {
@@ -197,7 +229,7 @@ impl ScreenEffects {
..
} => {
if let Some(rect) = sprite(name) {
out.push(gui(rect, rgba(*color), Blend::Alpha));
out.push(gui(rect, rgba(*color), Blend::Alpha, 0));
}
}
_ => {}
@@ -243,8 +275,10 @@ mod tests {
},
);
let e = ScreenEffects::default();
let flags = HashMap::new();
let input = ScreenInputs {
sprites: &sprites,
flags: &flags,
aspect: 1.6,
partial: 0.0,
block_overlay: None,
@@ -255,5 +289,80 @@ mod tests {
let quads = e.build(&input);
assert_eq!(quads.len(), 1);
assert_eq!(quads[0].blend, Blend::Vignette);
assert_eq!(quads[0].sampling, 0);
// A black vignette (faded out in daylight) changes no pixel: no quad.
// Below 1/255 the colour's channels are 0; a border warning tints it.
for (brightness, warning, drawn) in [(0.003, 0.0, 0), (0.004, 0.0, 1), (0.0, 0.5, 1)] {
let overlays = [crate::hud_overlays::vignette(320, 240, brightness, warning)];
let input = ScreenInputs {
block_overlay: None,
gui_overlays: &overlays,
..input
};
assert_eq!(e.build(&input).len(), drawn, "{brightness} {warning}");
}
}
#[test]
fn standalone_textures_sample_by_their_metadata() {
let rect = Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 16,
};
let sprites: HashMap<_, _> = ["misc/vignette", "misc/underwater", "block/stone"]
.map(|name| (name.to_owned(), rect))
.into();
let blur = TextureFlags {
blur: true,
clamp: false,
};
let clamp = TextureFlags {
blur: false,
clamp: true,
};
let flags: HashMap<_, _> = [
("misc/vignette".to_owned(), blur),
("misc/underwater".to_owned(), clamp),
// Atlas sprites ignore the texture section.
("block/stone".to_owned(), blur),
]
.into();
let quads = ScreenEffects::default().build(&ScreenInputs {
sprites: &sprites,
flags: &flags,
aspect: 1.6,
partial: 0.0,
block_overlay: Some("block/stone".to_owned()),
water: Some((1.0, 0.0, 0.0)),
on_fire: false,
gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)],
});
let sampling: Vec<_> = quads.iter().map(|q| q.sampling).collect();
assert_eq!(sampling, [0, SAMPLE_CLAMP, SAMPLE_BLUR]);
}
#[test]
fn mcmeta_texture_section() {
let parse = TextureFlags::from_mcmeta;
assert_eq!(
parse(r#"{"texture":{"blur":true}}"#),
Some(TextureFlags {
blur: true,
clamp: false
})
);
assert_eq!(
parse(r#"{"texture":{"clamp":true,"mipmap_strategy":"mean"}}"#),
Some(TextureFlags {
blur: false,
clamp: true
})
);
// Defaults (false, false) or no section: the default sampler.
assert_eq!(parse(r#"{"texture":{"blur":false}}"#), None);
assert_eq!(parse(r#"{"animation":{}}"#), None);
assert_eq!(parse("not json"), None);
}
}
+1
View File
@@ -433,6 +433,7 @@ fn guests_see_each_other_and_the_world_entities() {
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
needs_sync: false,
};
let first = thread::spawn(move || {
let mut bot = connect(port, "Alex", false)?;
@@ -0,0 +1,93 @@
//! The Rust side of tools/test_stepped_interpolation_parity.py: replays the
//! harness's events (VanillaSteppedInterpolationOracle's input format) on
//! `SteppedInterpolation` and writes the entity after each one.
use horizon_world::stepped_interpolation::{Path, PosRot, Start, SteppedInterpolation};
use std::fmt::Write as _;
/// `Entity.setRot`: yaw and pitch wrapped, pitch clamped (`setXRot`).
fn set_rot(entity: &mut PosRot, yaw: f32, pitch: f32) {
entity.yaw = yaw % 360.0;
entity.pitch = (pitch % 360.0 % 360.0).clamp(-90.0, 90.0);
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let input = std::fs::read_to_string(&args[1]).expect("input");
let mut out = String::new();
let mut handler = SteppedInterpolation::new(0);
let mut entity = PosRot::default();
for line in input.lines() {
let f: Vec<&str> = line.split_whitespace().collect();
let num = |i: usize| f[i].parse::<f64>().expect("number");
let what = match f[0] {
"case" => {
handler = SteppedInterpolation::new(f[1].parse().expect("steps"));
entity = PosRot {
position: [num(2), num(3), num(4)],
yaw: f[5].parse().expect("yaw"),
pitch: f[6].parse().expect("pitch"),
};
"c"
}
"move" => {
let mut i = 2;
let path = match f[1] {
"L" => {
i += 3;
Some(Path::Linear([num(2), num(3), num(4)]))
}
"S" => {
let n: usize = f[2].parse().expect("count");
i = 3;
let mut steps = Vec::new();
for _ in 0..n {
steps.push((
[num(i), num(i + 1), num(i + 2)],
f[i + 3].parse().expect("ticks"),
));
i += 4;
}
Some(Path::Stepped(steps))
}
_ => None,
};
let rotation = (f[i] == "R").then(|| {
(
f[i + 1].parse().expect("yaw"),
f[i + 2].parse().expect("pitch"),
)
});
match handler.interpolate_to(entity, path, rotation) {
Start::Snap(at) => {
entity.position = at.position;
set_rot(&mut entity, at.yaw, at.pitch);
"s"
}
Start::Unchanged => "k",
Start::Interpolating => "i",
}
}
"tick" => match handler.interpolate() {
Some(at) => {
entity.position = at.position;
set_rot(&mut entity, at.yaw, at.pitch);
"t"
}
None => "n",
},
other => panic!("unknown event {other}"),
};
let p = entity.position;
writeln!(
out,
"{what} {:x} {:x} {:x} {:x} {:x}",
p[0].to_bits(),
p[1].to_bits(),
p[2].to_bits(),
entity.yaw.to_bits(),
entity.pitch.to_bits()
)
.expect("write");
}
std::fs::write(&args[2], out).expect("output");
}
+1
View File
@@ -137,6 +137,7 @@ pub mod player_equipment;
pub mod living_use_flags;
pub mod status_effect;
pub mod stepped_interpolation;
pub mod synced_values;
pub mod inventory_use;
@@ -0,0 +1,341 @@
//! How a client moves a living entity it doesn't simulate along the
//! positions its server sends (vanilla `SteppedInterpolationHandler`, which
//! `LivingEntity.createInterpolationHandler` gives every living entity on a
//! client): each position is a step the entity walks to in the type's update
//! interval (3 ticks for most mobs), one after the other, sped up while
//! steps pile up. A punched mob's first move, sent at once (`needsSync`),
//! thus takes three ticks to show, and the rest follow it.
use std::collections::VecDeque;
/// A position and rotation (`PositionAndRotation`).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PosRot {
pub position: [f64; 3],
pub yaw: f32,
pub pitch: f32,
}
impl PosRot {
/// `PositionAndRotation.is`: the same rotation and `Vec3.equals`
/// position (`Double.compare`, so -0.0 is not 0.0).
fn is(&self, position: [f64; 3], yaw: f32, pitch: f32) -> bool {
self.yaw == yaw && self.pitch == pitch && same_position(self.position, position)
}
}
/// `Vec3.equals`.
fn same_position(a: [f64; 3], b: [f64; 3]) -> bool {
(0..3).all(|i| a[i].to_bits() == b[i].to_bits())
}
/// `PositionPath`: where a move packet puts an entity, either straight
/// there or through the positions the server stepped it through, each
/// with the ticks it took.
#[derive(Clone, Debug, PartialEq)]
pub enum Path {
Linear([f64; 3]),
Stepped(Vec<([f64; 3], i32)>),
}
impl Path {
pub fn end(&self) -> [f64; 3] {
match self {
Path::Linear(p) => *p,
Path::Stepped(steps) => steps.last().map_or([0.0; 3], |s| s.0),
}
}
}
/// What the client does with the entity when a packet arrives.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Start {
/// Moves on to it over the coming ticks.
Interpolating,
/// Already headed there: nothing changes.
Unchanged,
/// Is put there at once (`snapTo`): types with no update interval.
Snap(PosRot),
}
/// `SteppedInterpolationHandler` and its `InterpolationData`.
#[derive(Clone, Debug)]
pub struct SteppedInterpolation {
/// `AbstractInterpolationHandler.interpolationSteps`: the type's
/// `updateInterval`.
steps: i32,
/// The data's own position and rotation: where the last packet said.
target: PosRot,
/// `lastStepPosRot`: where the step being walked started.
last: PosRot,
remaining: VecDeque<(PosRot, i32)>,
current_step_ticks: f32,
remaining_ticks: f32,
speed: f32,
}
/// `Mth.wrapDegrees(float)`.
fn wrap_degrees(degrees: f32) -> f32 {
let mut wrapped = degrees % 360.0;
if wrapped >= 180.0 {
wrapped -= 360.0;
}
if wrapped < -180.0 {
wrapped += 360.0;
}
wrapped
}
/// `Mth.lerp(float, float, float)`.
fn lerp(a: f32, from: f32, to: f32) -> f32 {
from + a * (to - from)
}
/// `Mth.rotLerp`.
fn rot_lerp(a: f32, from: f32, to: f32) -> f32 {
from + a * wrap_degrees(to - from)
}
impl SteppedInterpolation {
/// The handler of an entity type whose update interval is `steps` ticks.
pub fn new(steps: i32) -> Self {
Self {
steps,
target: PosRot::default(),
last: PosRot::default(),
remaining: VecDeque::new(),
current_step_ticks: 0.0,
remaining_ticks: 0.0,
speed: 1.0,
}
}
/// `hasActiveInterpolation`.
pub fn active(&self) -> bool {
!self.remaining.is_empty()
}
/// Where the entity is headed: the last packet's position and rotation
/// while interpolating (`AbstractInterpolationHandler.interpolateTo`'s
/// `current`), else where it is.
pub fn heading(&self, entity: PosRot) -> PosRot {
if self.active() { self.target } else { entity }
}
/// `AbstractInterpolationHandler.interpolateTo(path, yRot, xRot,
/// hasRotation)` for an entity at `entity`: a packet without a position
/// (`path` None) keeps the one it is headed for, one without a rotation
/// the rotation.
pub fn interpolate_to(
&mut self,
entity: PosRot,
path: Option<Path>,
rotation: Option<(f32, f32)>,
) -> Start {
let current = self.heading(entity);
let path = path.unwrap_or(Path::Linear(current.position));
let (yaw, pitch) = rotation.unwrap_or((current.yaw, current.pitch));
let end = path.end();
if self.steps == 0 {
self.cancel();
return Start::Snap(PosRot {
position: end,
yaw,
pitch,
});
}
if self.active() && self.target.is(end, yaw, pitch) {
return Start::Unchanged;
}
// SteppedInterpolationHandler.startInterpolating.
if !self.active() {
self.last = entity;
self.current_step_ticks = 1.0;
}
if same_position(end, self.target.position) {
self.add_step(
PosRot {
position: end,
yaw,
pitch,
},
self.steps,
);
} else {
self.add_steps(&path, yaw, pitch);
}
self.target = PosRot {
position: end,
yaw,
pitch,
};
Start::Interpolating
}
/// `cancel` (`InterpolationData.reset`).
pub fn cancel(&mut self) {
self.remaining.clear();
self.remaining_ticks = 0.0;
self.speed = 1.0;
}
/// `AbstractInterpolationHandler.interpolate`, once a client tick: where
/// the entity is put, or None when there is nothing to walk (and the
/// handler resets). The client moves the entity only this way, so the
/// target never needs the deltas `adjustInterpolationTargetFromDeltas`
/// would add.
pub fn interpolate(&mut self) -> Option<PosRot> {
if !self.active() {
self.cancel();
return None;
}
// doInterpolate: getNewPositionAndRotation, then advance by the
// level's relative tick speed (1 at the normal tick rate).
let at = self.new_position();
self.advance(1.0);
Some(at)
}
/// `InterpolationData.addStep`.
fn add_step(&mut self, step: PosRot, ticks: i32) {
self.remaining.push_back((step, ticks));
self.remaining_ticks += ticks as f32;
}
/// `InterpolationData.addSteps`: a stepped path's steps take their own
/// ticks, turning by the share of the path each one ends.
fn add_steps(&mut self, path: &Path, yaw: f32, pitch: f32) {
match path {
Path::Linear(p) => self.add_step(
PosRot {
position: *p,
yaw,
pitch,
},
self.steps,
),
Path::Stepped(steps) => {
if yaw == self.target.yaw && pitch == self.target.pitch {
for (p, ticks) in steps {
self.add_step(
PosRot {
position: *p,
yaw,
pitch,
},
*ticks,
);
}
return;
}
let total: i32 = steps.iter().map(|s| s.1).sum();
let mut offset = 0;
let (from_yaw, from_pitch) = (self.target.yaw, self.target.pitch);
for (p, ticks) in steps {
offset += ticks;
let a = offset as f32 / total as f32;
let step = PosRot {
position: *p,
yaw: rot_lerp(a, from_yaw, yaw),
pitch: lerp(a, from_pitch, pitch),
};
self.add_step(step, *ticks);
}
}
}
}
/// `InterpolationData.getNewPositionAndRotation`.
fn new_position(&mut self) -> PosRot {
while let Some(&(step, ticks)) = self.remaining.front() {
if self.current_step_ticks < ticks as f32 {
let a = self.current_step_ticks / ticks as f32;
let t = f64::from(a);
let (from, to) = (self.last.position, step.position);
return PosRot {
position: [0, 1, 2].map(|i| from[i] + (to[i] - from[i]) * t),
yaw: rot_lerp(a, self.last.yaw, step.yaw),
pitch: lerp(a, self.last.pitch, step.pitch),
};
}
self.current_step_ticks -= ticks as f32;
self.last = step;
self.remaining.pop_front();
}
self.target
}
/// `InterpolationData.advance`: faster while more than one update's
/// worth of steps waits.
fn advance(&mut self, ticks: f32) {
let steps = self.steps as f32;
let target_speed = (self.remaining_ticks / steps).max(1.0);
self.speed = lerp(1.0 / steps, self.speed, target_speed);
let moved = if ticks * self.speed < self.remaining_ticks {
ticks * self.speed
} else {
self.speed = 1.0;
self.remaining_ticks
};
self.current_step_ticks += moved;
self.remaining_ticks -= moved;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn at(x: f64) -> PosRot {
PosRot {
position: [x, 0.0, 0.0],
yaw: 0.0,
pitch: 0.0,
}
}
#[test]
fn a_position_takes_the_update_interval_to_reach() {
let mut h = SteppedInterpolation::new(3);
let mut entity = at(0.0);
h.interpolate_to(entity, Some(Path::Linear([0.3, 0.0, 0.0])), None);
let mut seen = Vec::new();
while let Some(p) = h.interpolate() {
entity = p;
seen.push((p.position[0] * 1000.0).round() / 1000.0);
}
assert_eq!(seen, [0.1, 0.2, 0.3]);
assert!(!h.active());
assert_eq!(entity.position[0], 0.3);
}
#[test]
fn steps_that_pile_up_are_walked_faster() {
let mut h = SteppedInterpolation::new(3);
let mut entity = at(0.0);
let mut ticks = 0;
for k in 1..=4 {
h.interpolate_to(entity, Some(Path::Linear([f64::from(k), 0.0, 0.0])), None);
if let Some(p) = h.interpolate() {
entity = p;
}
ticks += 1;
}
while let Some(p) = h.interpolate() {
entity = p;
ticks += 1;
}
// Four packets a tick apart: 12 ticks of steps, walked in fewer.
assert!(ticks < 12, "{ticks}");
assert_eq!(entity.position[0], 4.0);
}
#[test]
fn no_update_interval_snaps() {
let mut h = SteppedInterpolation::new(0);
let start = h.interpolate_to(
at(0.0),
Some(Path::Linear([2.0, 0.0, 0.0])),
Some((90.0, 0.0)),
);
assert_eq!(
start,
Start::Snap(PosRot {
position: [2.0, 0.0, 0.0],
yaw: 90.0,
pitch: 0.0
})
);
}
}
+3 -3
View File
@@ -4,7 +4,7 @@
## What is measured
One game is started per render distance (8, 16 and 32 chunks by default), each from a fresh world, so nothing generated by an earlier run is reused. In each game:
One game is started per window size (1280x720 and 1920x1080 by default) and render distance (8, 16 and 32 chunks by default), each from a fresh world, so nothing generated by an earlier run is reused. In each game:
1. **Start to the title screen.** Wall-clock time from starting the process to the first frame of the title screen with no loading overlay.
2. **Create the world.** A creative world named `PerfBench`, seed 1234, default world type and difficulty, created the way the game's own Create World does. **Start to in-world** is the time from starting the process until the player has spawned and every chunk around the spawn is loaded and drawn.
@@ -16,7 +16,7 @@ One game is started per render distance (8, 16 and 32 chunks by default), each f
- **Same machine, same run conditions.** Games run one at a time; the load average before and after each run and the machine (CPU, RAM, OS) are stored with the results. Runs on a machine doing other work are marked as such and not published.
- **Same settings, one file.** Every game gets the same `options.txt`, written by the driver: render distance, simulation distance 12, unlimited frame rate (`maxFps:260`), VSync off, FOV 70, automatic GUI scale, windowed, no pause on lost focus, and `inactivityFpsLimit:minimized` (both games otherwise drop to 30 FPS after a minute without input). Everything else stays at vanilla's defaults: Horizon reads vanilla's `options.txt` keys and its defaults match vanilla's (the options harness checks it), and Horizon's own settings (`horizon-graphics.txt`) are left at their defaults, which render as vanilla does.
- **Same resolution.** Both windows are 1280x720 (Horizon's default window; vanilla gets `--width 1280 --height 720`). The size each game actually renders at is stored with the results.
- **Same resolution.** Both games get the same window size, `--width` and `--height` (vanilla's own launch arguments, which Horizon takes too): 1280x720, the size results were first published at, then 1920x1080, the commonest screen; `--sizes` picks others. The size each game actually renders at is stored with the results: a compositor or screen smaller than the window can shrink it.
- **Same world and path.** Same seed and world type; same paths, yaw and pitch, same flight speed; the same steps in the same order. Vanilla is driven by a small dev-only Fabric mod (`mods/horizon/src/bench`), which only calls the game's own code: it creates the world with `WorldOpenFlows.createFreshLevel` as the Create World screen does, teleports with `/tp`, sets the time with `/time set`, and places the player on the path each frame as Horizon's `horizon-ctl fly` does.
- **Warm-up excluded.** Each scene's flight starts only after its chunks are loaded and drawn and 2 seconds have passed; the load itself is reported separately. JIT warm-up of the JVM during the first scene is part of vanilla's real behaviour and is not removed.
- **The same statistics code.** Horizon returns its raw frame times (`horizon-ctl fly ... raw`) and the vanilla mod writes its own; `stats()` in the driver computes every figure for both.
@@ -55,7 +55,7 @@ python3 tools/perf_bench.py --game vanilla-mods --label mods-mine
python3 tools/perf_bench.py --table horizon-mine vanilla-mine mods-mine
```
Options: `--distances 8,16`, `--scenes village,ocean`, `--seconds 20`, `--repeats 5`, `--heap 4G` (vanilla), `--offscreen` (Horizon, for locked or headless sessions). Results go to `benchmarks/perf/<label>-rd<N>.json`, one [benchmark report](benchmark-report.md) per render distance (the same format the game's `--benchmark` and the launcher write), with the load average before each game; each game's log, and the vanilla driver's event log, stay in `.local/perf-bench/`. Keep the machine otherwise idle, plugged in, and the window on a screen.
Options: `--distances 8,16`, `--sizes 1920x1080`, `--scenes village,ocean`, `--seconds 20`, `--repeats 5`, `--heap 4G` (vanilla), `--offscreen` (Horizon, for locked or headless sessions). Results go to `benchmarks/perf/<label>-rd<N>.json` at 1280x720 and `<label>-1080p-rd<N>.json` at 1920x1080 (other sizes `<label>-<W>x<H>-rd<N>.json`; `--table` takes those labels), one [benchmark report](benchmark-report.md) per window size and render distance (the same format the game's `--benchmark` and the launcher write), with the load average before each game; each game's log, and the vanilla driver's event log, stay in `.local/perf-bench/`. Keep the machine otherwise idle, plugged in, and the window on a screen.
## Results
@@ -655,7 +655,8 @@ public final class VanillaDispenserOracle {
*/
static List<String> respawnAt(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception {
var config = new net.minecraft.server.level.ServerPlayer.RespawnConfig(
net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), pos, 0.0F, 0.0F), op.get("forced").getAsBoolean());
net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), pos,
op.has("yaw") ? op.get("yaw").getAsFloat() : 0.0F, 0.0F), op.get("forced").getAsBoolean());
Method find = net.minecraft.server.level.ServerPlayer.class.getDeclaredMethod("findRespawnAndUseSpawnBlock",
ServerLevel.class, net.minecraft.server.level.ServerPlayer.RespawnConfig.class, boolean.class);
find.setAccessible(true);
@@ -0,0 +1,148 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import net.minecraft.core.PositionAndRotation;
import net.minecraft.world.entity.PositionPath;
import net.minecraft.world.entity.PositionStep;
import net.minecraft.world.phys.Vec3;
/**
* How a client walks a living entity along the positions its server sends: the unmodified
* {@code SteppedInterpolationHandler.InterpolationData} (setStartingPoint, addStep, addSteps,
* getNewPositionAndRotation, advance, reset), driven the way
* {@code AbstractInterpolationHandler.interpolateTo} / {@code interpolate} and
* {@code SteppedInterpolationHandler.startInterpolating} / {@code doInterpolate} drive it, with the
* entity's own {@code setPos} / {@code setRot}. The handler's entity hooks are out of scope: the
* entity moves only by its interpolation (no deltas to adjust) at the normal tick rate.
*
* <p>Input (args[0]), one event a line: {@code case STEPS X Y Z YAW PITCH} (a fresh entity there
* with a handler of that many interpolation steps), {@code move L X Y Z} or {@code move S N
* (X Y Z TICKS)xN} or {@code move N} (no position), then {@code R YAW PITCH} or {@code -} (no
* rotation), and {@code tick}. Output (args[1]): the entity after every event.
*/
public final class VanillaSteppedInterpolationOracle {
private static Method method(Class<?> owner, String name, Class<?>... types) throws Exception {
Method m = owner.getDeclaredMethod(name, types);
m.setAccessible(true);
return m;
}
private static String hex(double v) {
return Long.toHexString(Double.doubleToRawLongBits(v));
}
private static String hex(float v) {
return Integer.toHexString(Float.floatToRawIntBits(v));
}
public static void main(String[] args) throws Exception {
Class<?> dataClass = Class.forName("net.minecraft.world.entity.SteppedInterpolationHandler$InterpolationData");
Constructor<?> create = dataClass.getDeclaredConstructor();
create.setAccessible(true);
Method advance = method(dataClass, "advance", float.class, int.class);
Method addStep = method(dataClass, "addStep", Vec3.class, float.class, float.class, int.class);
Method addSteps = method(dataClass, "addSteps", PositionPath.class, float.class, float.class, int.class);
Method setStartingPoint = method(dataClass, "setStartingPoint", Vec3.class, float.class, float.class);
Method next = method(dataClass, "getNewPositionAndRotation");
Method reset = method(dataClass, "reset");
Field remaining = dataClass.getDeclaredField("remainingSteps");
remaining.setAccessible(true);
Object data = null;
int steps = 0;
Vec3 pos = Vec3.ZERO;
float yRot = 0;
float xRot = 0;
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) {
for (String line : Files.readAllLines(Path.of(args[0]))) {
String[] f = line.trim().split(" ");
int i = 1;
String what;
switch (f[0]) {
case "case" -> {
data = create.newInstance();
steps = Integer.parseInt(f[1]);
pos = new Vec3(Double.parseDouble(f[2]), Double.parseDouble(f[3]), Double.parseDouble(f[4]));
yRot = Float.parseFloat(f[5]);
xRot = Float.parseFloat(f[6]);
what = "c";
}
case "move" -> {
PositionPath path = null;
switch (f[i++]) {
case "L" -> {
path = PositionPath.of(new Vec3(Double.parseDouble(f[i]), Double.parseDouble(f[i + 1]), Double.parseDouble(f[i + 2])));
i += 3;
}
case "S" -> {
int n = Integer.parseInt(f[i++]);
List<PositionStep> list = new ArrayList<>();
for (int k = 0; k < n; k++) {
list.add(new PositionStep(new Vec3(Double.parseDouble(f[i]), Double.parseDouble(f[i + 1]), Double.parseDouble(f[i + 2])), Integer.parseInt(f[i + 3])));
i += 4;
}
path = PositionPath.stepped(List.copyOf(list));
}
default -> {
}
}
boolean hasRotation = f[i].equals("R");
float y = hasRotation ? Float.parseFloat(f[i + 1]) : 0;
float x = hasRotation ? Float.parseFloat(f[i + 2]) : 0;
boolean active = !((List<?>) remaining.get(data)).isEmpty();
PositionAndRotation.Mutable target = (PositionAndRotation.Mutable) data;
// AbstractInterpolationHandler.interpolateTo(path, yRot, xRot, hasRotation).
PositionAndRotation current = active ? target : PositionAndRotation.of(pos, yRot, xRot);
if (path == null) path = PositionPath.of(current.position());
if (!hasRotation) {
y = current.yRot();
x = current.xRot();
}
Vec3 end = path.endPosition();
if (steps == 0) {
// snapTo, then cancel.
pos = end;
yRot = y % 360.0F;
xRot = Math.clamp(x % 360.0F % 360.0F, -90.0F, 90.0F);
reset.invoke(data);
what = "s";
} else if (active && target.is(end, y, x)) {
what = "k";
} else {
// SteppedInterpolationHandler.startInterpolating.
if (!active) setStartingPoint.invoke(data, pos, yRot, xRot);
if (Objects.equals(end, target.position())) addStep.invoke(data, end, y, x, steps);
else addSteps.invoke(data, path, y, x, steps);
target.set(end, y, x);
what = "i";
}
}
case "tick" -> {
// AbstractInterpolationHandler.interpolate.
if (((List<?>) remaining.get(data)).isEmpty()) {
reset.invoke(data);
what = "n";
} else {
PositionAndRotation t = (PositionAndRotation) next.invoke(data);
pos = t.position();
yRot = t.yRot() % 360.0F;
xRot = Math.clamp(t.xRot() % 360.0F % 360.0F, -90.0F, 90.0F);
advance.invoke(data, 1.0F, steps);
what = "t";
}
}
default -> throw new IllegalArgumentException(line);
}
out.println(what + " " + hex(pos.x) + " " + hex(pos.y) + " " + hex(pos.z) + " " + hex(yRot) + " " + hex(xRot));
}
}
}
}
+8
View File
@@ -38,6 +38,14 @@ class PerfBenchStatsTests(unittest.TestCase):
self.assertIsNone(frames("x", 0, []))
json.dumps(s)
def test_window_sizes_name_their_reports(self):
from tools.perf_bench import SIZES, parse_sizes, size_label
self.assertEqual(parse_sizes("1280x720,1920X1080"), [(1280, 720), (1920, 1080)])
self.assertEqual(SIZES, [(1280, 720), (1920, 1080)])
self.assertEqual(size_label("horizon-m4", 1280, 720), "horizon-m4")
self.assertEqual(size_label("horizon-m4", 1920, 1080), "horizon-m4-1080p")
self.assertEqual(size_label("horizon-m4", 2560, 1080), "horizon-m4-2560x1080")
def test_one_options_file_sets_the_render_distance(self):
self.assertEqual(OPTIONS["renderDistance"].format(distance=16), "16")
self.assertEqual(OPTIONS["graphicsPreset"], '"custom"')
+4
View File
@@ -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); }
+483 -27
View File
@@ -146,6 +146,28 @@ 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: a vindicator's axe disables the host's, then the guest's, raised shield: the server
counts its 5 s cooldown down once a tick (#1316).
- beds: the host and the guest each set their respawn point at a bed and die elsewhere: they
stand up beside the bed, or, when the bed is gone or boxed in by stone, come back at
the world spawn (#1308).
- 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).
@@ -187,7 +209,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', 'styles', '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', 'hands', 'lightning', 'riding', 'mounts', 'levels']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', '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', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
class Game:
@@ -2661,6 +2683,441 @@ 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
# Sneaking from before the player lands on the magma.
held = ['shift'] if case == 'sneaking' else []
for k in held:
game.raw('key', k, 'down')
game.wait(5)
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 = ['w'] if walk else []
for k in keys:
game.raw('key', k, 'down')
game.wait(60)
# Read before letting go: standing up on the magma would hurt.
after = own(game)['health']
for k in keys + held:
game.raw('key', k, 'up')
game.wait(10)
seen[f'{game.name}-{case}'] = (before, after)
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_beds(host, guest, out):
"""A bed sets the respawn point (day or night): respawning stands the player up beside it; a bed
that is gone, or boxed in by stone so there is nowhere to stand up, sends the player to the world
spawn instead (#1308). The host, then the guest, each for the three beds."""
hx, hy, hz = (int(v // 1) for v in pos_of(host))
host('command', command='gamerule respawn_radius 0')
host('command', command=f'setworldspawn {hx} {hy} {hz}')
host('command', command='time set 1000')
seen = {}
try:
for game, dz in ((host, -6), (guest, 6)):
game('command', command='gamemode survival')
x, y, z = hx + 12, hy, hz + dz
for case in ('intact', 'gone', 'boxed'):
game('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 3} minecraft:stone')
game('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 3} minecraft:air')
game('command', command=f'setblock {x} {y} {z} minecraft:red_bed[facing=east,part=foot]')
game('command', command=f'setblock {x + 1} {y} {z} minecraft:red_bed[facing=east,part=head]')
game('command', command=f'tp @s {x + 0.5} {y} {z + 1.5}')
game.wait(20)
game.raw('interact', x + 1, y, z)
game.wait(10)
# Die elsewhere, by the world spawn.
game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 3.5}')
game.wait(10)
if case == 'gone':
game('command', command=f'fill {x} {y} {z} {x + 1} {y} {z} minecraft:air')
elif case == 'boxed':
game('command', command=f'fill {x - 2} {y} {z - 2} {x + 3} {y + 2} {z + 2} minecraft:stone replace minecraft:air')
game.wait(5)
game('command', command='kill @s')
game.wait(20)
respawn_when_ready(game)
game.wait(60)
at = [round(v, 2) for v in pos_of(game)]
seen[f'{game.name}-{case}'] = {'at': at, 'bed': [x + 1, y, z], 'health': own(game)['health']}
game.shot(out, f'beds-{case}')
finally:
host('command', command='gamerule respawn_radius 10')
host('command', command='time set 1000')
for game in (host, guest):
game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 0.5}')
guest.wait(20)
for case, s in seen.items():
(px, py, pz), (bx, by, bz) = s['at'], s['bed']
if case.endswith('intact'):
near = ((px - bx - 0.5) ** 2 + (pz - bz - 0.5) ** 2) ** 0.5
assert near < 2.6 and abs(py - by) < 0.6, f'{case}: not beside its bed: {seen}'
else:
assert abs(px - (hx + 0.5)) < 1 and abs(pz - (hz + 0.5)) < 1, f'{case}: not at the world spawn: {seen}'
assert s['health'] > 0, f'{case}: died again after respawning: {seen}'
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."""
@@ -3492,33 +3949,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, 'styles': check_styles,
'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, 'styles': check_styles, '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, 'hands': check_hands, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts,
'levels': check_levels}
'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, 'hands': check_hands,
'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts,
'worldspawn': check_world_spawn, 'beds': check_beds, '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):
+36 -13
View File
@@ -256,6 +256,23 @@ def write_options(game_dir, distance, version=None):
return text
# Window sizes of the standard set (every game gets --width/--height): 720p,
# the size results were first published at, and 1080p, the commonest screen.
SIZES = [(1280, 720), (1920, 1080)]
def parse_sizes(text):
""""1280x720,1920x1080" as [(1280, 720), (1920, 1080)]."""
return [tuple(int(v) for v in size.lower().split("x")) for size in text.split(",") if size]
def size_label(label, width, height):
"""Reports at 1280x720 keep the plain label; other sizes add theirs: horizon-m4-1080p, or -2560x1080."""
if (width, height) == SIZES[0]:
return label
return f"{label}-{height}p" if width * 9 == height * 16 else f"{label}-{width}x{height}"
def scene_list(args):
picked = args.scenes.split(",") if args.scenes else [s[0] for s in SCENES]
return [s for s in SCENES if s[0] in picked]
@@ -375,6 +392,9 @@ def run_horizon(args, distance):
client = Path(args.build).resolve() / "horizon-client"
command = [str(client), "--resources", str(Path(args.resources).resolve()),
"--control-socket", str(sock), "--no-pause", "--weather", "clear", "--time", "6000"]
if (args.width, args.height) != SIZES[0]:
# 1280x720 is Horizon's own window; builds before --width open only that one.
command += ["--width", str(args.width), "--height", str(args.height)]
if args.offscreen:
command.append("--offscreen")
for carry in dev_mods(args):
@@ -796,8 +816,8 @@ def main():
p.add_argument("--seconds", type=float, default=12.0, help="flight duration per scene")
p.add_argument("--settle", type=float, default=2.0, help="seconds held at the start before each flight")
p.add_argument("--timeout", type=float, default=300.0, help="seconds allowed for each load")
p.add_argument("--width", type=int, default=1280, help="vanilla window width (Horizon's is 1280x720)")
p.add_argument("--height", type=int, default=720)
p.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES),
help="window sizes, each a set of reports (default 1280x720 and 1920x1080)")
p.add_argument("--heap", default="2G", help="vanilla -Xmx (the official launcher's default is 2G)")
p.add_argument("--offscreen", action="store_true",
help="Horizon renders into a texture and does not wait for the window (locked macOS sessions)")
@@ -817,17 +837,20 @@ def main():
args.label = args.label or f"{args.game}-{platform.node().split('.')[0]}"
WORK.mkdir(parents=True, exist_ok=True)
run = {"horizon": run_horizon, "neoforge": run_neoforge}.get(args.game, run_vanilla)
for d in [int(x) for x in args.distances.split(",")]:
runs = []
for _ in range(args.repeats):
load_before = os.getloadavg()
result = run(args, d)
result["load_before"], result["load_after"] = load_before, os.getloadavg()
runs.append(result)
out = ROOT / "benchmarks/perf" / f"{args.label}-rd{d}.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report(args, d, runs, app(args)), indent=1) + "\n")
print(out)
label = args.label
for args.width, args.height in parse_sizes(args.sizes):
args.label = size_label(label, args.width, args.height)
for d in [int(x) for x in args.distances.split(",")]:
runs = []
for _ in range(args.repeats):
load_before = os.getloadavg()
result = run(args, d)
result["load_before"], result["load_after"] = load_before, os.getloadavg()
runs.append(result)
out = ROOT / "benchmarks/perf" / f"{args.label}-rd{d}.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report(args, d, runs, app(args)), indent=1) + "\n")
print(out)
def app(args):
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Compare how a client walks a living entity along its server's positions with vanilla.
Vanilla's unmodified SteppedInterpolationHandler.InterpolationData (VanillaSteppedInterpolationOracle
drives it as the handler does) and horizon-world's SteppedInterpolation replay the same packets and
client ticks: move packets with and without a position or rotation, straight or stepped paths,
repeats of the one the entity is headed for, packets a tick apart that pile up and others after it
stopped, for update intervals of 1 to 3 ticks, plus a punched pig's knockback as the server sends it
(its first move at once, `needsSync`, then every update interval). The entity's position and rotation
after every event must match bit for bit. The handler's entity hooks (deltas, passengers) are out of
scope.
"""
import os
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
# A pig punched on flat ground, its positions on the server tick by tick (knockback 0.4 along x).
KNOCKBACK = [(0.0, 0.0), (0.3032, 0.3608), (0.4638, 0.636), (0.6049, 0.8273), (0.7279, 0.9363), (0.8345, 0.9648),
(0.926, 0.9143), (1.0037, 0.7864), (1.0688, 0.5827), (1.1223, 0.3046), (1.1654, 0.0), (1.1147, 0.0),
(0.9968, 0.0), (0.8418, 0.0), (0.6664, 0.0)]
def position(rng, p):
return [round(v + rng.uniform(-0.6, 0.6), rng.choice([2, 4, 17])) for v in p]
def rotation(rng):
return [round(rng.uniform(-400, 400), rng.choice([0, 1, 3])), round(rng.uniform(-120, 120), rng.choice([0, 2]))]
def cases(count, seed):
rng = random.Random(seed)
lines = []
for interval in (1, 2, 3):
# The knockback: a packet for the hit tick's move, then every interval (each phase).
for phase in range(interval):
lines.append(f'case {interval} 10.5 64.0 0.5 90.0 0.0')
for k in range(1, len(KNOCKBACK)):
if k == 1 or (k + phase) % interval == 0:
x, y = KNOCKBACK[k]
lines.append(f'move L {10.5 + x!r} {64 + y!r} 0.5 -')
lines.append('tick')
lines += ['tick'] * 6
for _ in range(count):
p = [rng.uniform(-100, 100), rng.uniform(-64, 300), rng.uniform(-100, 100)]
yaw, pitch = rotation(rng)
lines.append(f'case {rng.choice([1, 2, 3, 3, 3])} {p[0]!r} {p[1]!r} {p[2]!r} {yaw!r} {pitch!r}')
last = None
for _ in range(rng.randrange(1, 40)):
if rng.random() < 0.45:
lines.append('tick')
continue
if last is not None and rng.random() < 0.15:
line = last # the same packet again
else:
if rng.random() < 0.1:
line = 'move N'
elif rng.random() < 0.2:
n = rng.randrange(1, 5)
steps = []
for _ in range(n):
p = position(rng, p)
steps.append(f'{p[0]!r} {p[1]!r} {p[2]!r} {rng.randrange(1, 4)}')
line = f'move S {n} ' + ' '.join(steps)
else:
p = position(rng, p) if rng.random() < 0.9 else p
line = f'move L {p[0]!r} {p[1]!r} {p[2]!r}'
rot = rotation(rng) if rng.random() < 0.6 else None
line += f' R {rot[0]!r} {rot[1]!r}' if rot else ' -'
last = line
lines.append(line)
lines += ['tick'] * rng.choice([0, 1, 1, 2, 3, 6])
return lines
def main():
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / 'stepped-interpolation-parity'
build.mkdir(parents=True, exist_ok=True)
classes = build / 'classes'
classes.mkdir(exist_ok=True)
events = build / 'events.txt'
events.write_text('\n'.join(cases(3000, 1374)) + '\n', encoding='utf-8')
classpath = os.pathsep.join(map(str, [jars['client'], *libraries]))
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSteppedInterpolationOracle.java'
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
'-cp', classpath, '-d', str(classes), str(oracle)], check=True)
subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + classpath,
'dev.horizonlab.parity.VanillaSteppedInterpolationOracle', str(events), str(build / 'vanilla.txt')],
check=True)
subprocess.run(['cargo', 'run', '--quiet', '--release', '-p', 'horizon-world', '--example',
'stepped_interpolation_fixture', '--', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True)
matched = base.compare(build / 'vanilla.txt', build / 'rust.txt')
print(f'Stepped interpolation parity passed: {matched} entity positions and rotations match vanilla')
if __name__ == '__main__':
main()
+55 -1
View File
@@ -23,7 +23,9 @@ explode elsewhere (`RespawnAnchorBlock`, through the stand-in level's real
`ServerExplosion`, with water at the anchor). Respawn cases call
`ServerPlayer.findRespawnAndUseSpawnBlock` on an anchor among blocks
(`RespawnAnchorBlock.findStandUpPosition` through `DismountHelper`): the
position, the yaw that faces the anchor and the charge it uses. Beds and straw
position, the yaw that faces the anchor and the charge it uses; others on a
bed's head set from some yaw (`AbstractBedBlock.findStandUpPosition`: intact,
bunk, only the foot left or gone, crowded around and on top). Beds and straw
beds clicked (head or foot, whole or broken) in the Nether and the End blow up
or fall apart (`AbstractBedBlock.useWithoutItem` under the dimension's
`bed_rule`: `BedBlock.destroyOnUse`, `StrawBedBlock.destroyBed`). Horizon runs
@@ -90,6 +92,52 @@ BED_COLORS = ['red', 'white', 'black', 'cyan', 'lime']
FACINGS = {'north': (0, -1), 'south': (0, 1), 'west': (-1, 0), 'east': (1, 0)}
def bed_respawn_case(rng, states, case):
"""Respawning at a bed's head set from some yaw: intact, a bunk bed, only the foot left or
gone, with blocks around and on it, in the Overworld (and a few in the Nether or the End)."""
name = 'straw_bed' if rng.random() < 0.15 else rng.choice(BED_COLORS) + '_bed'
facing = rng.choice(list(FACINGS))
fx, fz = FACINGS[facing]
bed = {}
kept = rng.random()
if kept < 0.75:
bed[(0, 0, 0)] = states.get(name, facing=facing, part='head', occupied='false')
elif kept < 0.85:
bed[(0, 0, 0)] = states.get(rng.choice(['stone', 'white_carpet', 'oak_slab']))
if kept < 0.9 or rng.random() < 0.5:
bed[(-fx, 0, -fz)] = states.get(name, facing=facing, part='foot', occupied='false')
if rng.random() < 0.2:
# A bunk bed: another bed below.
bed[(0, -1, 0)] = states.get(name, facing=facing, part='head', occupied='false')
bed[(-fx, -1, -fz)] = states.get(name, facing=facing, part='foot', occupied='false')
crowd = rng.choice([0.0, 0.1, 0.3, 0.6, 0.95])
cells = [[*k, v] for k, v in bed.items()]
if (0, 0, 0) not in bed:
cells.insert(0, [0, 0, 0, states.get('air')])
for dy in (-2, -1, 0, 1, 2):
for dx in range(-3, 4):
for dz in range(-3, 4):
if (dx, dy, dz) in bed or (dx, dy, dz) == (0, 0, 0):
continue
if dy == -1 and (dx, 0, dz) in bed:
name2 = 'stone'
elif dy < 0:
name2 = rng.choice(['stone'] * 8 + STAND)
elif rng.random() < crowd:
name2 = rng.choice(['stone'] * 4 + STAND)
else:
continue
if name2 == 'air':
continue
state = states.any(rng, name2) if name2 in ('oak_trapdoor', 'oak_slab', 'snow', 'campfire', 'water', 'ladder') else states.get(name2)
cells.append([dx, dy, dz, state])
if rng.random() < 0.1:
case['dim'] = rng.choice(['nether', 'end'])
yaw = rng.choice([0.0, 90.0, -90.0, 180.0, round(rng.uniform(-720, 720), rng.choice([0, 2]))])
case['respawn_at'] = {'forced': rng.random() < 0.15, 'consume': rng.random() < 0.8, 'yaw': yaw}
case['cells'] = cells
def bed_case(rng, states, case):
"""A bed (or straw bed) clicked in the Nether or the End, among blocks."""
name = 'straw_bed' if rng.random() < 0.25 else rng.choice(BED_COLORS) + '_bed'
@@ -224,6 +272,12 @@ def cases(facts, count, seed):
case['mode'] = 'dispense'
yield case
continue
if rng.random() < 0.1:
bed_respawn_case(rng, states, case)
case['items'] = []
case['mode'] = 'dispense'
yield case
continue
if rng.random() < 0.15:
anchor_case(rng, states, case)
case['items'] = []