diff --git a/crates/horizon-client/src/attribute_updates.rs b/crates/horizon-client/src/attribute_updates.rs index b81db5835..1dcc21028 100644 --- a/crates/horizon-client/src/attribute_updates.rs +++ b/crates/horizon-client/src/attribute_updates.rs @@ -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; diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index cfbdb0636..65536d710 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -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; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2d185b40e..67bab7846 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -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, /// `--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::()?.max(1), + "--height" => o.window_size[1] = value.parse::()?.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), diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 3ee069778..41d2276f5 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -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::>(), }) @@ -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) }, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 0a51f6119..c5a3fc456 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -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()), diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 3de4341ad..752785084 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -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 { diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 222e59229..6dd02893d 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2700,6 +2700,7 @@ impl Game<'_> { equipment: Vec::new(), attributes: Vec::new(), precise: false, + needs_sync: false, }) } } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index c3f34ebd3..d62c8ccc2 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -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); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..bdbfa3fc6 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -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 = { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index b0ea90ce8..ecf8f39ff 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -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>, @@ -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>, 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; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 5f46f7c21..631498edd 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -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, } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 488d134f3..c0809a647 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -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, lerps: HashMap, + /// Living entities' `SteppedInterpolationHandler`s. + stepped: HashMap, /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. head_lerps: HashMap, /// 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, 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 diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4ad9db548..e947d2af5 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -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, diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 9b6ecc203..392a53964 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -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 { + // 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) diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 1b1ec3a6d..1e94ec995 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -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}"); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index c14a32e2c..f1cc3393d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -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); } } diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 2537949d0..82e606947 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -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 { + 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, pub width: u32, pub height: u32, pub sprites: HashMap, + /// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others + /// sample as vanilla's defaults (nearest, repeat). + pub flags: HashMap, 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) { } /// A packed atlas image: sprite name, size and RGBA pixels. type PackedImage = (String, u32, u32, Vec); +/// `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)> { + let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { 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 = 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 = 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 = diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index b7484a7be..f3da6bf8f 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -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); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 948de7e20..4236280cd 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -153,6 +153,9 @@ pub struct Guest { /// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots). pub ender_items: Vec>, 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, 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, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index de3326b02..c31b3c929 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -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, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 24a4a9d65..475979d81 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -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; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index db2ebeb60..76f622d9c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -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; diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index ebbfabf6b..d5b3c7091 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -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; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..339cb86b8 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -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 = 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, entered: &mut Vec<(i32, BlockPos)>, max_iterations: i32, + damage_only: bool, ) -> Result { 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 diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index a9bb33678..fc3c63c77 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -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(()); } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 191509780..dd86c8f9c 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -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 diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index 62cb2ee6c..e70aeb896 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -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; -@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, @location(0) uv: vec2, @location(1) @interpolate(flat) rect: vec4, @location(2) color: vec4, + // With clamp-to-edge, the sprite's first and last texel centres. + @location(3) @interpolate(flat) edges: vec4, } @vertex fn vs_screen(@location(0) pos: vec2, @location(1) uv: vec2, @location(2) rect: vec4, @location(3) color: vec4) -> Out { @@ -15,12 +28,24 @@ struct Out { out.uv = uv; out.rect = rect; out.color = color; + let half = 0.5 / vec2(textureDimensions(atlas)); + out.edges = vec4(rect.xy + half, rect.zw - half); return out; } fn sample(in: Out) -> vec4 { - 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 { let c = sample(in); diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs index bc7756453..269a534e7 100644 --- a/crates/horizon-client/src/screen_effects.rs +++ b/crates/horizon-client/src/screen_effects.rs @@ -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, + /// `.png.mcmeta` sampling of the standalone textures among `sprites`. + pub flags: &'a HashMap, 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 { 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); } } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index bd22d6e0a..4f5f17a3b 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -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)?; diff --git a/crates/horizon-world/examples/stepped_interpolation_fixture.rs b/crates/horizon-world/examples/stepped_interpolation_fixture.rs new file mode 100644 index 000000000..d2228d8b5 --- /dev/null +++ b/crates/horizon-world/examples/stepped_interpolation_fixture.rs @@ -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 = 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::().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"); +} diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs index 819262d46..b6d05ecf6 100644 --- a/crates/horizon-world/src/lib.rs +++ b/crates/horizon-world/src/lib.rs @@ -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; diff --git a/crates/horizon-world/src/stepped_interpolation.rs b/crates/horizon-world/src/stepped_interpolation.rs new file mode 100644 index 000000000..a7157d90a --- /dev/null +++ b/crates/horizon-world/src/stepped_interpolation.rs @@ -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, + 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 { + 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 + }) + ); + } +} diff --git a/docs/benchmark.md b/docs/benchmark.md index 99ce40130..8bcc432e0 100644 --- a/docs/benchmark.md +++ b/docs/benchmark.md @@ -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/