diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/firework_tooltip_fixture.rs index 196fa9955..7f10278b7 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/firework_tooltip_fixture.rs @@ -1,7 +1,7 @@ //! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the //! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line; //! the `#resources` line names the prepared resources for en_us). -use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language}; +use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; fn main() -> Result<(), Box> { @@ -12,8 +12,9 @@ fn main() -> Result<(), Box> { .find_map(|l| l.strip_prefix("#resources ")) .map(PathBuf::from) .ok_or("no #resources line")?; - let language = Language::load(&[&root], "en_us"); - let translate = |key: &str| language.get(key).map(str::to_owned); + // Use the inventory's filtered translations so missing tooltip keys are caught. + let enchantments = Enchantments::load(&root); + let translate = |key: &str| enchantments.translate(key).map(str::to_owned); let mut output = String::new(); for line in input.lines().filter(|l| !l.starts_with('#')) { let stack = parse_stack(line)?.ok_or("empty stack")?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/held_drop_fixture.rs index 87ca9870c..a0c5d92ba 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/held_drop_fixture.rs @@ -14,13 +14,22 @@ fn main() { for count in [0, 1, 4, 64] { let mut slot = Some(ItemStack::new("minecraft:stone", count)); let mut dropped = 0; + let mut swings = 0; + let mut packets = 0; for _ in 0..2 { if let Some(stack) = take_held_drop(&mut slot, all, mode == GameMode::Spectator) { dropped += stack.count; + swings += 1; } - println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped); + if mode != GameMode::Spectator { + packets += 1; + } + println!( + "{} {dropped} {swings} {packets}", + slot.as_ref().map_or(0, |s| s.count), + ); } } } diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index 9f8e99899..b8c56b28c 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -3,6 +3,7 @@ //! what the render thread pays for it in `Streaming::update`. //! //! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] //! //! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x //! at that speed for T seconds while frames run at F per second. Each phase reports @@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator; type Result = std::result::Result>; +fn cpu_seconds() -> f64 { + std::fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|stat| { + let fields = stat + .rsplit_once(')')? + .1 + .split_whitespace() + .collect::>(); + Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) + }) + .unwrap_or(0.0) +} + #[derive(Default)] struct Phase { updates: Vec, local: (u64, u64), uploads: usize, + stage_samples: [u64; 7], + cpu_start: f64, } impl Phase { fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + if self.updates.is_empty() { + self.cpu_start = cpu_seconds(); + } let before = LOCAL.with(Cell::get); let started = Instant::now(); let (uploads, _) = streaming.update(world); @@ -89,6 +109,9 @@ impl Phase { self.local.1 += after.1 - before.1; self.uploads += uploads.len(); drop(uploads); + for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { + *sum += count as u64; + } } fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { let mut sorted = self.updates.clone(); @@ -106,6 +129,16 @@ impl Phase { at(0.99), sorted.last().copied().unwrap_or(0.0), ); + println!( + "BENCH {}", + serde_json::json!({ + "phase": name, "wall_s": wall.as_secs_f64(), + "cpu_s": cpu_seconds() - self.cpu_start, + "chunks": streaming.generated_total - generated, "sections": self.uploads, + "updates": self.updates.len(), "update_ms": total, + "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), + }) + ); if TRACK { println!( " update allocations: {} ({:.1} MiB)", @@ -142,6 +175,22 @@ fn main() -> Result<()> { let fly = flag("--fly", 0.0); let seconds = flag("--seconds", 10.0); let hz = flag("--hz", 240.0); + let dimension = args + .iter() + .position(|a| a == "--dimension") + .and_then(|i| args.get(i + 1)) + .map(|d| { + if d.contains(':') { + d.clone() + } else { + format!("minecraft:{d}") + } + }) + .unwrap_or_else(|| "minecraft:overworld".into()); + let center = ( + flag("--center-x", 0.0) as i32, + flag("--center-z", 0.0) as i32, + ); let assets = Arc::new(Assets::load(&root)?); let render = Arc::new(assets.reload(&root)?); @@ -154,11 +203,12 @@ fn main() -> Result<()> { models::load_visibility(&root, assets.registry)?, )?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::new( + let terrain = Arc::new(VanillaTerrain::for_dimension( &root.join("worldgen"), assets.registry, &biomes, seed, + &dimension, )?); let context = Arc::new(WorkerContext { assets, @@ -170,8 +220,12 @@ fn main() -> Result<()> { let mut world = World::new(facts.air, seed); let mut streaming = Streaming::new(terrain, context, threads); streaming.radius = radius; - streaming.center = (0, 0); - println!("{threads} workers, radius {radius}, seed {seed}"); + streaming.center = center; + streaming.nether_shading = dimension == "minecraft:the_nether"; + streaming.sky_light = dimension != "minecraft:the_nether"; + println!( + "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" + ); let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); // Fill: update as often as the game would uncapped, until settled. @@ -198,12 +252,12 @@ fn main() -> Result<()> { let mut behind = Vec::new(); while started.elapsed().as_secs_f64() < seconds { let next = Instant::now() + frame; - let x = (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, 0); + let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, center.1); phase.update(&mut streaming, &mut world); // Columns within 2 chunks of the player still missing their meshes. let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) .count(); behind.push(near); diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 039ea658f..ca2ea6f5c 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -193,6 +193,8 @@ impl Enchantments { || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") + || k.starts_with("item.minecraft.firework_rocket.") + || k.starts_with("item.minecraft.firework_star.") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1c9b21b49..af92089d8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4849,6 +4849,9 @@ impl Game<'_> { self.draw_chat(&mut batch); self.draw_tab_list(&mut batch); } + // Screen.extractBlurredBackground blurs the world and HUD, while the + // screen's background, widgets, toasts and debug overlay stay sharp. + batch.blur_at = batch.vertices.len() as u32; match self.screen { Screen::Paused if self.pause_menu => self.draw_pause_menu(&mut batch), // PauseScreen(false): only its title, at the top. @@ -10018,9 +10021,8 @@ impl Game<'_> { }; level_loading::draw(batch, atlas, Some(&status), Some(self.loading_progress)); } - /// `Screen.extractBlurredBackground` over the panorama: every classic - /// screen of the title menus but the title itself (`TitleScreen` - /// doesn't blur), when `menuBackgroundBlurriness` is at least 1. + /// `Screen.extractBlurredBackground` over the panorama or the world and + /// HUD, when `menuBackgroundBlurriness` is at least 1. fn menu_blur(&self) -> Option { let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other); let blurred = !horizon_client::ui_theme::horizon() @@ -10028,7 +10030,10 @@ impl Game<'_> { || self.title.as_ref().is_some_and(|t| { self.screen == Screen::Options || !matches!(t.mode, horizon_client::title::Mode::Main) - })); + }) + || (self.title.is_none() + && self.player.is_some() + && self.screen.blurs_background(self.pause_menu))); let radius = self.settings.menu_blur as f32; (blurred && radius >= 1.0).then_some(radius) } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ea8137776..9d1e82e56 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -7,7 +7,7 @@ //! client predicts its own movement; the server stays authoritative for //! everything else. use super::{Dim, Game, Mining, Screen}; -use horizon_client::first_person::Hand; +use horizon_client::first_person::{Hand, SwingAnimation}; use horizon_client::{ Result, chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, @@ -332,6 +332,11 @@ impl Game<'_> { progress: 0.0, total: 0, }; + // The connected client never opens a server world (single player also + // joins here), so load the registries its argument parsers and local + // suggestions need before receiving the server's command tree. + self.ui.registries = Default::default(); + self.build_registries(); self.ui.registries.permission = 0; self.ui.chat.clear(); self.screen = Screen::Playing; @@ -3458,10 +3463,8 @@ impl Game<'_> { sequence: seq, })); if progress >= 1.0 { + // startDestroyBlock: instant survival breaks have no destroy delay. self.predict_break(hit.pos, state, seq); - if let Some(r) = self.remote.as_mut() { - r.destroy_delay = 5; - } return; } if let Some(r) = self.remote.as_mut() { @@ -3638,7 +3641,15 @@ impl Game<'_> { self.predict_use(&changes, seq); } if held_block { - self.with_hand(hand, Game::swing_arm); + if reacts + || held + .as_ref() + .is_some_and(|stack| self.remote_can_place(&hit, stack)) + { + self.with_hand(hand, Game::swing_arm); + } + // BlockItem.place returns FAIL when placement is rejected: + // stop this click without trying the item or the other hand. return true; } return reacts; @@ -3696,7 +3707,11 @@ impl Game<'_> { /// container, and the blocks it changed. Vanilla's client runs it on its /// own level first; this runs it on a copy, and `predict_use` keeps the /// changes it predicts. - fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) { + fn remote_block_reacts( + &mut self, + hit: &super::Hit, + held: Option<&ItemStack>, + ) -> (bool, DryUse) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { @@ -3711,26 +3726,53 @@ impl Game<'_> { [-1, 0, 0] => Direction::West, _ => Direction::East, }; - let mut level = DryLevel { - world: &self.world, - changed: HashMap::new(), - random: horizon_core::random::LegacyRandom::new(0), - sounds: Vec::new(), + let player = self.use_context(); + self.with_level(|b, level, _| { + let mut level = DryLevel::new(level); + let reacts = b + .use_item_on( + &mut level, + &mut horizon_world::level::Ticks::default(), + horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face, + horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]), + player, + held.map(|s| &*s.item), + ) + .consumes_action(); + (reacts, (level.changed.into_iter().collect(), level.sounds)) + }) + } + + /// Run BlockItem.place on a disposable level before predicting its swing. + /// The real level supplies collision shapes and building-blocking entities; + /// block writes, random draws, scheduled ticks and events stay in the preview. + fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool { + if !self.may_build() { + return false; + } + let ctx = horizon_world::level::PlaceContext { + clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face: horizon_core::geometry::Direction::ALL[face_direction(hit.face) as usize], + hit: Vec3::new(hit.point[0], hit.point[1], hit.point[2]), + inside: hit.face == [0; 3], + yaw: self.yaw, + pitch: self.pitch, + sneaking: self.keys.contains(&KeyCode::ShiftLeft), + item: stack.item.to_string(), + can_use_game_master_blocks: self.can_use_game_master_blocks(), }; - let reacts = self - .res - .behaviours() - .use_item_on( - &mut level, - &mut horizon_world::level::Ticks::default(), - horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), - face, - horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]), - self.use_context(), - held.map(|s| &*s.item), + self.with_level(|b, level, _| { + let mut level = DryLevel::new(level); + matches!( + b.place_block( + &mut level, + &mut horizon_world::level::Ticks::default(), + &ctx + ), + horizon_world::level::PlaceOutcome::Placed { .. } ) - .consumes_action(); - (reacts, (level.changed.into_iter().collect(), level.sounds)) + }) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether @@ -3985,23 +4027,26 @@ impl Game<'_> { Ok(true) } KeyCode::KeyQ => { + if self.spectator() { + return Ok(true); + } let all = self.keys.contains(&KeyCode::ControlLeft); + // MultiPlayerGameMode.dropItem: predict removal before sending + // the action, then swing only if a nonempty stack was removed. + let dropped = horizon_client::items::take_held_drop( + &mut self.inventory[self.selected], + all, + false, + ); self.send(S::PlayerAction(play::PlayerAction { action: if all { 4 } else { 5 }, pos: [0; 3], direction: 0, sequence: 0, })); - // Inventory.removeFromSelected (prediction). - let slot = &mut self.inventory[self.selected]; - if let Some(s) = slot { - if all || s.count <= 1 { - *slot = None; - } else { - s.count -= 1; - } + if dropped.is_some() { + self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); } - self.swing_arm(); Ok(true) } KeyCode::KeyE => { @@ -4678,7 +4723,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 { /// The client's world for a guess at what a click does: reads go to the /// world, writes stay here and are dropped. struct DryLevel<'w> { - world: &'w horizon_client::world::World, + base: &'w dyn horizon_world::level::LevelAccess, changed: HashMap, random: horizon_core::random::LegacyRandom, /// The sounds the use plays (a door's creak). @@ -4708,6 +4753,17 @@ pub(super) fn hand_operated(name: &str) -> bool { || name == "lever" } +impl<'w> DryLevel<'w> { + fn new(base: &'w dyn horizon_world::level::LevelAccess) -> Self { + Self { + base, + changed: HashMap::new(), + random: horizon_core::random::LegacyRandom::new(0), + sounds: Vec::new(), + } + } +} + impl horizon_world::level::LevelAccess for DryLevel<'_> { fn emit(&mut self, event: horizon_world::level::LevelEvent) { if let horizon_world::level::LevelEvent::Sound { @@ -4724,7 +4780,7 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> { self.changed .get(&pos) .copied() - .unwrap_or_else(|| self.world.block(pos.x, pos.y, pos.z)) + .unwrap_or_else(|| self.base.block_state(pos)) } fn set_raw( &mut self, @@ -4736,13 +4792,31 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> { Some(previous) } fn is_loaded(&self, pos: horizon_core::position::BlockPos) -> bool { - self.world.loaded(pos.x, pos.z) + self.base.is_loaded(pos) + } + fn min_y(&self) -> i32 { + self.base.min_y() + } + fn max_y(&self) -> i32 { + self.base.max_y() + } + fn block_light(&self, pos: horizon_core::position::BlockPos) -> i32 { + self.base.block_light(pos) + } + fn sky_light(&self, pos: horizon_core::position::BlockPos) -> i32 { + self.base.sky_light(pos) + } + fn sky_darken(&self) -> i32 { + self.base.sky_darken() + } + fn is_unobstructed(&self, pos: horizon_core::position::BlockPos, state: BlockStateId) -> bool { + self.base.is_unobstructed(pos, state) } fn random(&mut self) -> &mut horizon_core::random::LegacyRandom { &mut self.random } fn game_time(&self) -> i64 { - self.world.game_time + self.base.game_time() } } @@ -4858,6 +4932,110 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_ mod tests { use super::Game; + #[test] + fn placement_preview_checks_obstruction_without_changing_the_level() { + use super::DryLevel; + use horizon_core::{position::BlockPos, random::LegacyRandom}; + use horizon_world::{ + level::{ + Behaviours, LevelAccess, PlaceContext, PlaceOutcome, Ticks, data::load_registry, + }, + registry::BlockStateId, + }; + + struct Level { + air: BlockStateId, + stone: BlockStateId, + obstructed: bool, + loaded: bool, + ceiling: i32, + } + impl LevelAccess for Level { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + if pos == BlockPos::new(0, 0, 0) { + self.stone + } else { + self.air + } + } + fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option { + panic!("preview must not write to the live level"); + } + fn is_loaded(&self, _: BlockPos) -> bool { + self.loaded + } + fn max_y(&self) -> i32 { + self.ceiling + } + fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool { + assert_eq!(pos, BlockPos::new(0, 1, 0)); + !self.obstructed + } + fn random(&mut self) -> &mut LegacyRandom { + panic!("preview must not advance the live level's random source"); + } + fn game_time(&self) -> i64 { + 0 + } + } + + // As with the LAN tests, prepared game resources are optional locally. + let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !resources.join("block-behaviours.json").exists() { + return; + } + let registry = load_registry(&resources).unwrap(); + let behaviours = Behaviours::load(®istry, &resources).unwrap(); + let mut base = Level { + air: registry.default_state("minecraft:air").unwrap(), + stone: registry.default_state("minecraft:stone").unwrap(), + obstructed: false, + loaded: true, + ceiling: 320, + }; + for item in [ + "minecraft:stone", + "minecraft:oak_slab", + "minecraft:oak_door", + // GrowingPlantHeadBlock.getStateForPlacement draws a random age. + "minecraft:twisting_vines", + ] { + let ctx = PlaceContext { + clicked_pos: BlockPos::new(0, 0, 0), + face: horizon_core::geometry::Direction::Up, + hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5), + inside: false, + yaw: 0.0, + pitch: 45.0, + sneaking: false, + item: item.into(), + can_use_game_master_blocks: false, + }; + for (obstructed, loaded, ceiling) in [ + (false, true, 320), + (true, true, 320), + (false, false, 320), + (false, true, 1), + ] { + base.obstructed = obstructed; + base.loaded = loaded; + base.ceiling = ceiling; + let valid = !obstructed && loaded && ceiling > 1; + let mut preview = DryLevel::new(&base); + let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx); + assert_eq!( + matches!(outcome, PlaceOutcome::Placed { .. }), + valid, + "{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}" + ); + assert_eq!(preview.changed.is_empty(), !valid); + assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air); + } + } + } + #[test] fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() { // InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand. diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index cecd8d46f..07eacfb49 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -7,6 +7,24 @@ use horizon_client::{ ui, }; +impl Screen { + /// Screen.extractBackground for non-isInGameUi screens, and + /// PauseScreen.extractBackground only when showPauseMenu is true. + pub(super) fn blurs_background(self, pause_menu: bool) -> bool { + match self { + Self::Paused => pause_menu, + Self::Options | Self::Stats | Self::Advancements | Self::WorldOptions => true, + Self::Playing + | Self::GameModeSwitcher + | Self::Chat + | Self::Creative + | Self::Inventory + | Self::Dead + | Self::CommandBlock => false, + } + } +} + /// PauseScreen buttons: (x, y, width, label key, action id, active). /// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { @@ -334,7 +352,34 @@ impl Game<'_> { #[cfg(test)] mod tests { - use super::pause_buttons; + use super::{Screen, pause_buttons}; + + #[test] + fn menu_blur_matches_vanilla_screen_backgrounds() { + for screen in [ + Screen::Options, + Screen::Stats, + Screen::Advancements, + Screen::WorldOptions, + ] { + assert!(screen.blurs_background(false)); + assert!(screen.blurs_background(true)); + } + assert!(Screen::Paused.blurs_background(true)); + assert!(!Screen::Paused.blurs_background(false)); + for screen in [ + Screen::Playing, + Screen::GameModeSwitcher, + Screen::Chat, + Screen::Creative, + Screen::Inventory, + Screen::Dead, + Screen::CommandBlock, + ] { + assert!(!screen.blurs_background(true)); + assert!(!screen.blurs_background(false)); + } + } #[test] fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 14c040c5c..3de07b17b 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3841,9 +3841,19 @@ impl Renderer { let first = debug_depth + debug_top; pass.draw(0..4, first..first + crosshair); } - if let Some(radius) = frame.menu_blur - && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) - { + let menu_blur = frame + .menu_blur + .filter(|_| self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)); + let blur_at = menu_blur.map_or(0, |_| frame.hud.blur_at); + self.hud.draw_range( + &mut encoder, + &view_target, + &self.depth, + frame.hud, + [self.config.width, self.config.height], + 0..blur_at, + ); + if let Some(radius) = menu_blur { let format = self.config.format; let device = &self.device; self.menu_blur @@ -3875,12 +3885,13 @@ impl Renderer { grade, ); } - self.hud.draw( + self.hud.draw_range( &mut encoder, &view_target, &self.depth, frame.hud, [self.config.width, self.config.height], + blur_at..frame.hud.vertices.len() as u32, ); if culling && let Some(cull) = &mut self.cull { cull.end(&self.device, &mut encoder); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 6c2b3a006..b4bfe72ac 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -365,6 +365,8 @@ pub struct HudBatch { pub patches: Vec, /// Vertex ranges with another blend or depth/scissor state, in order. pub blends: Vec<(std::ops::Range, Blend)>, + /// Screen's first vertex: the preceding HUD is part of its blurred background. + pub blur_at: u32, } /// How a run of HUD vertices blends and tests depth. #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -400,6 +402,7 @@ impl HudBatch { height: (window[1] as f32 / scale as f32).ceil(), patches: Vec::new(), blends: Vec::new(), + blur_at: 0, } } /// Draw the vertices added since `start` with the inverting blend. @@ -452,6 +455,14 @@ impl HudBatch { } out } + fn runs_in(&self, vertices: std::ops::Range) -> Vec<(std::ops::Range, Blend)> { + let mut runs = self.runs(); + for (range, _) in &mut runs { + *range = range.start.max(vertices.start)..range.end.min(vertices.end); + } + runs.retain(|(range, _)| !range.is_empty()); + runs + } /// `AbstractContainerScreen.init`: center in integer GUI coordinates. pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) { ( @@ -1080,7 +1091,26 @@ impl HudRenderer { batch: &HudBatch, size: [u32; 2], ) { - if batch.vertices.is_empty() || size.contains(&0) { + self.draw_range( + encoder, + target, + depth, + batch, + size, + 0..batch.vertices.len() as u32, + ); + } + /// Draw part of the prepared batch, preserving its blend/depth runs. + pub fn draw_range( + &self, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + depth: &wgpu::TextureView, + batch: &HudBatch, + size: [u32; 2], + vertices: std::ops::Range, + ) { + if vertices.is_empty() || size.contains(&0) { return; } let attachments = [Some(wgpu::RenderPassColorAttachment { @@ -1092,7 +1122,7 @@ impl HudRenderer { store: wgpu::StoreOp::Store, }, })]; - let runs = batch.runs(); + let runs = batch.runs_in(vertices); let mut at = 0; while at < runs.len() { let clip = match runs[at].1 { @@ -1331,6 +1361,33 @@ mod tests { ] ); } + + #[test] + fn blur_boundary_splits_blend_runs_without_losing_or_repeating_vertices() { + let mut batch = HudBatch::new([854, 480]); + for _ in 0..5 { + batch.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0); + } + batch.blends = vec![ + (6..18, Blend::Invert), + (18..24, Blend::Depth([0, 0, 10, 10])), + ]; + for split in [0, 6, 12, 18, 24, 30] { + let before = batch.runs_in(0..split); + let after = batch.runs_in(split..30); + let actual: Vec<_> = before + .into_iter() + .chain(after) + .flat_map(|(range, blend)| range.map(move |v| (v, blend))) + .collect(); + let expected: Vec<_> = batch + .runs() + .into_iter() + .flat_map(|(range, blend)| range.map(move |v| (v, blend))) + .collect(); + assert_eq!(actual, expected, "blur at {split}"); + } + } #[test] fn container_origins_use_java_integer_division() { // Odd scaled dimensions, odd image sizes and an oversized panel. @@ -1342,6 +1399,7 @@ mod tests { height: height as f32, patches: Vec::new(), blends: Vec::new(), + blur_at: 0, }; for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] { assert_eq!( diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index bf398edfc..ca6ff481b 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -609,6 +609,65 @@ mod tests { assert!(container_lines(&ItemStack::new("minecraft:chest", 1), &name, &lang).is_empty()); } + #[test] + fn fireworks_use_loaded_tooltip_translations() { + let root = std::env::temp_dir().join(format!( + "horizon-firework-tooltip-language-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(), + )); + let dir = root.join("assets/minecraft/lang"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("en_us.json"), + serde_json::to_vec(&serde_json::json!({ + "item.minecraft.firework_rocket.flight_duration": "Flight Duration: %s", + "item.minecraft.firework_rocket.multiple_stars": "%s x %s", + "item.minecraft.firework_star.shape.small_ball": "Small Ball", + "item.minecraft.firework_star.red": "Red", + "item.minecraft.firework_star.custom_color": "Custom", + "item.minecraft.firework_star.fade_to": "Fade to", + "item.minecraft.firework_star.trail": "Trail", + "item.minecraft.firework_star.flicker": "Twinkle", + })) + .unwrap(), + ) + .unwrap(); + let enchantments = crate::enchant::Enchantments::load(&root); + std::fs::remove_dir_all(&root).unwrap(); + let translate = |key: &str| enchantments.translate(key).map(str::to_owned); + let mut rocket = ItemStack::new("minecraft:firework_rocket", 1); + assert_eq!(firework_lines(&rocket, &translate), ["Flight Duration: 1"]); + let explosion = crate::particles::FireworkExplosion { + colors: vec![0xB3312C], + fade: vec![0x123456], + trail: true, + twinkle: true, + ..Default::default() + }; + rocket.data_mut().fireworks = Some((3, vec![explosion.clone(), explosion.clone()])); + assert_eq!( + firework_lines(&rocket, &translate), + [ + "Flight Duration: 3", + "2 x Small Ball", + " Red", + " Fade to Custom", + " Trail", + " Twinkle", + ] + ); + let mut star = ItemStack::new("minecraft:firework_star", 1); + star.data_mut().firework_explosion = Some(explosion); + assert_eq!( + firework_lines(&star, &translate), + ["Small Ball", "Red", "Fade to Custom", "Trail", "Twinkle"] + ); + } + #[test] fn amounts_use_two_decimals_at_most() { assert_eq!(format_amount(8.0), "8"); diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 2e1eb8455..0cfe3c585 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1305,8 +1305,73 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { }; layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); } - let above = [if sky_light { 15 } else { 0 }; 256]; - crate::light::light_from_layers(chunk, &layers, above, sky_light); + // Uniform saved layers need no expanded allocation. Both nibbles of + // each byte must match, not merely the bytes across the layer. + let uniform_layer = |layer: &[u8]| { + let first = layer[0]; + (first & 15 == first >> 4 && layer.iter().all(|&v| v == first)).then_some(first & 15) + }; + let mut above = [if sky_light { 15 } else { 0 }; 256]; + for (si, (sky, block)) in layers.into_iter().enumerate().rev() { + let sky = sky.filter(|_| sky_light); + let sky_uniform = sky.map_or_else( + || above.iter().all(|&v| v == above[0]).then_some(above[0]), + uniform_layer, + ); + let block_uniform = block.map_or(Some(0), uniform_layer); + let section = Arc::make_mut(&mut chunk.sections[si]); + if let (Some(s), Some(b)) = (sky_uniform, block_uniform) { + section.light = Light::Uniform(s << 4 | b); + above.fill(s); + } else { + let mut data = Box::new([0u8; 4096]); + match (sky, block) { + (Some(sky), Some(block)) => { + for ((pair, &s), &b) in + data.as_chunks_mut::<2>().0.iter_mut().zip(sky).zip(block) + { + pair[0] = s << 4 | (b & 15); + pair[1] = (s & 0xf0) | (b >> 4); + } + } + (Some(sky), None) => { + for (pair, &s) in data.as_chunks_mut::<2>().0.iter_mut().zip(sky) { + pair[0] = s << 4; + pair[1] = s & 0xf0; + } + } + (None, Some(block)) => { + for (i, (pair, &b)) in data + .as_chunks_mut::<2>() + .0 + .iter_mut() + .zip(block) + .enumerate() + { + pair[0] = above[(i * 2) & 255] << 4 | (b & 15); + pair[1] = above[(i * 2 + 1) & 255] << 4 | (b >> 4); + } + } + (None, None) => { + for layer in data.as_chunks_mut::<256>().0 { + for (v, &s) in layer.iter_mut().zip(&above) { + *v = s << 4; + } + } + } + } + if let Some(sky) = sky { + for (pair, &s) in above.as_chunks_mut::<2>().0.iter_mut().zip(sky) { + pair[0] = s & 15; + pair[1] = s >> 4; + } + } + section.light = Light::Full(data); + } + section.compact(); + } + chunk.lit = true; + chunk.light_loaded = true; } type RegionCache = Mutex>>>>; @@ -3892,6 +3957,151 @@ mod tests { assert!(!unlit.lit && !unlit.light_loaded); } #[test] + fn saved_light_matches_reference_for_layers_and_metadata() { + fn reference(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { + if tag.get("isLightOn") != Some(&Tag::Byte(1)) { + return; + } + let Some(Tag::List(sections)) = tag.get("sections") else { + return; + }; + let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS]; + for section in sections { + let Some(y) = number(section.get("Y")) else { + continue; + }; + let si = y as i32 - (MIN_Y >> 4); + if !(0..SECTIONS as i32).contains(&si) { + continue; + } + let layer = |name: &str| match section.get(name) { + Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]), + _ => None, + }; + layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); + } + let above = [if sky_light { 15 } else { 0 }; 256]; + crate::light::light_from_layers(chunk, &layers, above, sky_light); + } + + let section = |y: Tag, sky: Option, block: Option| { + let mut entries = vec![("Y", y)]; + if let Some(v) = sky { + entries.push(("SkyLight", v)); + } + if let Some(v) = block { + entries.push(("BlockLight", v)); + } + Tag::compound(entries) + }; + let root = |sections| { + Tag::compound([ + ("isLightOn", Tag::Byte(1)), + ("sections", Tag::List(sections)), + ]) + }; + let check = |tag: &Tag| { + for sky_light in [false, true] { + let mut expected = Chunk::empty(-3, 5); + let s = Arc::make_mut(&mut expected.sections[0]); + s.light = Light::Full(Box::new([0xab; 4096])); + s.blocks.set(0, 1); + s.blocks.set(0, 0); + s.biomes.set(0, 1); + s.biomes.set(0, 0); + let mut actual = expected.clone(); + reference(tag, &mut expected, sky_light); + load_light(tag, &mut actual, sky_light); + assert_eq!( + (actual.lit, actual.light_loaded), + (expected.lit, expected.light_loaded) + ); + for (a, b) in actual.sections.iter().zip(&expected.sections) { + assert_eq!( + std::mem::discriminant(&a.light), + std::mem::discriminant(&b.light) + ); + assert_eq!( + format!("{:?}", a.blocks.to_wire()), + format!("{:?}", b.blocks.to_wire()) + ); + assert_eq!( + format!("{:?}", a.biomes.to_wire()), + format!("{:?}", b.biomes.to_wire()) + ); + for i in 0..4096 { + assert_eq!(a.light(i), b.light(i), "index {i}, sky {sky_light}"); + } + } + } + }; + for tag in [ + Tag::compound(Vec::<(&str, Tag)>::new()), + Tag::compound([("isLightOn", Tag::Byte(0))]), + Tag::compound([("isLightOn", Tag::Byte(2))]), + Tag::compound([("isLightOn", Tag::Int(1)), ("sections", Tag::List(vec![]))]), + Tag::compound([("isLightOn", Tag::Byte(1)), ("sections", Tag::Int(0))]), + root(vec![]), + ] { + check(&tag); + } + // Cover every repeated byte, including 0xF0/0x0F: a uniform byte + // array need not hold uniform nibbles. + for byte in 0..=255u8 { + check(&root(vec![section( + Tag::Byte(19), + Some(Tag::ByteArray(vec![byte; 2048])), + Some(Tag::ByteArray(vec![255 - byte; 2048])), + )])); + } + // Every pair of uniform sky/block nibble values, with missing + // sections below inheriting the stored bottom row. + for sky in 0..16u8 { + for block in 0..16u8 { + check(&root(vec![section( + Tag::Byte(1), + Some(Tag::ByteArray(vec![sky * 17; 2048])), + Some(Tag::ByteArray(vec![block * 17; 2048])), + )])); + } + } + for length in [0, 1, 2047, 2048, 2049] { + for invalid in [ + Tag::Int(1), + Tag::List(vec![]), + Tag::ByteArray(vec![0xf0; length]), + ] { + check(&root(vec![section( + Tag::Byte(-4), + Some(invalid.clone()), + Some(invalid), + )])); + } + } + let varied: Vec = (0..2048) + .map(|i| (i as u8).wrapping_mul(73).wrapping_add(31)) + .collect(); + check(&root(vec![ + section(Tag::Byte(-5), Some(Tag::ByteArray(varied.clone())), None), + section(Tag::Byte(20), Some(Tag::ByteArray(varied.clone())), None), + section( + Tag::String("19".into()), + Some(Tag::ByteArray(varied.clone())), + None, + ), + section(Tag::Byte(19), Some(Tag::ByteArray(varied.clone())), None), + section(Tag::Byte(17), None, Some(Tag::ByteArray(varied.clone()))), + section(Tag::Byte(-4), Some(Tag::ByteArray(varied.clone())), None), + // Last duplicate wins, even when its arrays have wrong types. + section( + Tag::Byte(-4), + Some(Tag::Int(15)), + Some(Tag::ByteArray(vec![7; 2047])), + ), + section(Tag::Byte(0), None, Some(Tag::ByteArray(varied))), + ])); + } + #[test] fn level_round_trips_through_the_vanilla_files() { let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs index 23360b637..2eb433600 100644 --- a/crates/horizon-world/examples/chunkgen_bench.rs +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -3,7 +3,7 @@ //! chunkgen_bench [--seed S] [--size N] [--threads T] //! [--center CX CZ] [--verify ] [--no-decorate] //! [--dimension overworld|the_nether|the_end] -//! [--warmup] [--json] [--no-map] +//! [--warmup] [--json] [--no-map] [--snapshot PATH] use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -275,6 +275,7 @@ fn main() -> Result<(), Error> { let resources = PathBuf::from(args.next().expect("client resource directory")); let (mut seed, mut size, mut threads, mut center) = (0i64, 16i32, 2usize, (0, 0)); let mut parity = None; + let mut snapshot_path = None; let mut decorate = true; let (mut warmup, mut json, mut map) = (false, false, true); let mut dimension = String::from("minecraft:overworld"); @@ -287,6 +288,7 @@ fn main() -> Result<(), Error> { "--threads" => threads = next().parse()?, "--center" => center = (next().parse()?, next().parse()?), "--verify" => parity = Some(PathBuf::from(next())), + "--snapshot" => snapshot_path = Some(PathBuf::from(next())), "--no-decorate" => decorate = false, "--warmup" => warmup = true, "--json" => json = true, @@ -409,6 +411,9 @@ fn main() -> Result<(), Error> { .into_iter() .map(|slot| slot.into_inner().unwrap()) .collect(); + if let Some(path) = &snapshot_path { + snapshot(&chunks, path, "terrain")?; + } if decorate && size >= 3 { let totals = Mutex::new(DecorateStats::default()); let start = Instant::now(); @@ -494,6 +499,9 @@ fn main() -> Result<(), Error> { ); } } + if let Some(path) = &snapshot_path { + snapshot(&chunks, path, "decorated")?; + } let mut structures = BTreeMap::<(String, i32, i32), [[i32; 3]; 2]>::new(); for chunk in chunks.iter().flatten() { for (name, start, min, max) in chunk.structures() { @@ -570,3 +578,75 @@ fn main() -> Result<(), Error> { ); Ok(()) } + +// Diagnostic only: full ordered chunk state, outside performance measurements. +fn snapshot(chunks: &[Option], path: &Path, phase: &str) -> Result<(), Error> { + use std::io::Write; + let mut out = + std::io::BufWriter::new(fs::File::create(format!("{}-{phase}.bin", path.display()))?); + for chunk in chunks.iter().flatten() { + let terrain = &chunk.terrain; + writeln!( + out, + "chunk {:?} {:?} {} {:?} {:?}", + chunk.position(), + terrain.generation_stage(), + chunk.is_decorated(), + chunk.structures(), + terrain.below_zero_retrogen().map(|v| v.to_nbt()) + )?; + for section in 0..terrain.height() as usize / 16 { + let data = terrain.section(section).unwrap(); + writeln!(out, "section {section} {:?}", data.to_nbt()?)?; + for index in 0..4096 { + out.write_all(&data.get(index)?.0.to_le_bytes())?; + } + } + // Compare public reads too, including all-air section behavior. + for y in terrain.min_y()..terrain.min_y() + terrain.height() { + for z in 0..16 { + for x in 0..16 { + out.write_all(&terrain.block(x, y, z).0.to_le_bytes())?; + } + } + } + for y in (terrain.min_y() >> 2)..((terrain.min_y() + terrain.height()) >> 2) { + for z in 0..4 { + for x in 0..4 { + writeln!( + out, + "biome {}", + chunk.biome_at( + chunk.position().x * 16 + x * 4, + y * 4, + chunk.position().z * 16 + z * 4 + ) + )?; + } + } + } + for kind in HeightmapType::ALL { + writeln!( + out, + "heightmap {kind:?} {:?}", + terrain.heightmap(kind).map(|m| m.raw_data()) + )?; + } + writeln!(out, "post {:?}", terrain.postprocessing())?; + writeln!(out, "blockticks {:?}", terrain.block_ticks().pack(0))?; + writeln!(out, "fluidticks {:?}", terrain.fluid_ticks().pack(0))?; + for (position, tag) in &chunk.block_entities { + writeln!(out, "blockentity {position:?}")?; + let bytes = + horizon_world::nbt::write_network(&Tag::Compound(tag.clone()), Default::default())?; + out.write_all(&(bytes.len() as u64).to_le_bytes())?; + out.write_all(&bytes)?; + } + let entities = Tag::List(chunk.entities.iter().cloned().map(Tag::Compound).collect()); + let bytes = horizon_world::nbt::write_network(&entities, Default::default())?; + out.write_all(&(bytes.len() as u64).to_le_bytes())?; + out.write_all(&bytes)?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/level_place_fixture.rs b/crates/horizon-world/examples/level_place_fixture.rs index a8f00edd1..13595726d 100644 --- a/crates/horizon-world/examples/level_place_fixture.rs +++ b/crates/horizon-world/examples/level_place_fixture.rs @@ -20,6 +20,7 @@ struct Cells { cells: HashMap, air: BlockStateId, random: LegacyRandom, + obstructed: bool, } impl LevelAccess for Cells { fn block_state(&self, pos: BlockPos) -> BlockStateId { @@ -37,6 +38,9 @@ impl LevelAccess for Cells { fn game_time(&self) -> i64 { 0 } + fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool { + !self.obstructed + } } fn main() -> Result<(), Box> { @@ -68,6 +72,7 @@ fn main() -> Result<(), Box> { cells, air, random: LegacyRandom::new(case["seed"].as_i64().unwrap()), + obstructed: case["obstructed"].as_bool().unwrap_or(false), }; let mut ticks = Ticks::new(0); for x in -2..=2 { diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 28b45ea44..2595173ad 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -995,6 +995,46 @@ where worker.terrain_context = context; result } + /// With the native End source there are no badlands/iceberg extensions. + /// Disabled aquifers with air as their default fluid can only add lava or + /// air to the default solid, so this constant rule would rewrite each solid + /// with the state it already has. Check their imported material flags too. + /// Noise filling already built the WG maps; these writes add no fluid marks. + fn identity_end_surface(&self, pos: ChunkPos) -> bool { + if !matches!(self.source, ResolvedBiomeSource::End(_)) + // At wrapped block coordinates the ordinary biome-region lookup + // can fail; retain that lookup and its error outside this range. + || ![pos.x, pos.z].into_iter().all(|c| { + c.checked_mul(16).is_some_and(|b| { + b.checked_sub(16).is_some() && b.checked_add(31).is_some() + }) + }) + || self.aquifer.is_some() + || Some(self.settings.default_block) + != self.data.registry.default_state("minecraft:end_stone") + || Some(self.settings.default_fluid) + != self.data.registry.default_state("minecraft:air") + || !self.data.states.get(self.settings.default_fluid).air + || !self + .data + .registry + .default_state("minecraft:lava") + .is_some_and(|lava| self.data.states.get(lava).fluid) + { + return false; + } + let mut rule = &self.rule; + // Restrict the shortcut to shallow block references; other rules still + // run their normal compilation, queries and error handling. + for _ in 0..32 { + match rule { + MaterialRule::Reference(next) => rule = next, + MaterialRule::Block(state) => return *state == self.settings.default_block, + _ => return false, + } + } + false + } fn generate_with_context( &self, worker: &mut WorkerState, @@ -1103,32 +1143,34 @@ where .map_err(stage("noise"))?; let generation = self.generation(); worker.timings.noise += lap(&mut clock); - build_surface( - &mut chunk, - self.rule.clone(), - SurfaceInputs:: { - generation, - noise_volume: volume, - root: self.root.clone(), - surface: SurfaceQueries { - pipeline: self, - temperatures: &mut worker.temperatures, - biome: Biomes::Region(&biomes), - uniform_biomes: Some(UniformSurfaceBiomes::new( - pos, - self.settings.level_min_y, - self.settings.level_height, - )), - possible: Some(possible), + if !self.identity_end_surface(pos) { + build_surface( + &mut chunk, + self.rule.clone(), + SurfaceInputs:: { + generation, + noise_volume: volume, + root: self.root.clone(), + surface: SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Region(&biomes), + uniform_biomes: Some(UniformSurfaceBiomes::new( + pos, + self.settings.level_min_y, + self.settings.level_height, + )), + possible: Some(possible), + }, + preliminary_surface: self.preliminary.clone(), + density_context: context, + write_min_y: min, + write_max_y: min + height - 1, }, - preliminary_surface: self.preliminary.clone(), - density_context: context, - write_min_y: min, - write_max_y: min + height - 1, - }, - &self.extensions, - ) - .map_err(stage("surface"))?; + &self.extensions, + ) + .map_err(stage("surface"))?; + } worker.timings.surface += lap(&mut clock); let carvers = &data.biome_carvers; let mask = generate_carving_mask(self.seed, pos, generation, false, |origin| { @@ -2480,6 +2522,108 @@ impl GeneratorWorker { #[cfg(test)] mod tests { use super::*; + #[test] + fn end_identity_surface_matches_normal_surface_and_rejects_custom_rules() { + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry = Box::leak(Box::new(crate::level::data::load_registry(&root).unwrap())); + let data = GeneratorData::load(&root.join("worldgen"), registry).unwrap(); + let preset: Value = serde_json::from_str(&data.world_presets["minecraft:normal"]).unwrap(); + let settings: Value = serde_json::from_str(&data.settings["minecraft:end"]).unwrap(); + let mut pipeline = Pipeline::new( + data.clone(), + 12345, + LegacyRandom::new(12345), + &preset["dimensions"]["minecraft:the_end"]["generator"], + &settings, + false, + None, + ) + .unwrap(); + let mut worker = OverworldGenerator::for_world( + data.clone(), + 12345, + "minecraft:normal", + "minecraft:the_end", + false, + ) + .unwrap() + .worker(); + assert!(pipeline.identity_end_surface(ChunkPos::new(0, 0))); + for pos in [ + ChunkPos::new(0, 0), + ChunkPos::new(128, 128), + ChunkPos::new(-128, 192), + ChunkPos::new(1_875_000, -1_875_000), + ] { + let actual = pipeline.generate(&mut worker.state, pos).unwrap(); + let rule = pipeline.rule.clone(); + // A singleton sequence evaluates the same block rule through the full surface path. + pipeline.rule = MaterialRule::Sequence(vec![rule.clone()]); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + let expected = pipeline.generate(&mut worker.state, pos).unwrap(); + pipeline.rule = rule; + assert_eq!( + actual.terrain.generation_stage(), + expected.terrain.generation_stage() + ); + for section in 0..actual.terrain.height() as usize / 16 { + assert_eq!( + actual.terrain.section(section).unwrap().to_nbt().unwrap(), + expected.terrain.section(section).unwrap().to_nbt().unwrap() + ); + } + for kind in HeightmapType::ALL { + assert_eq!( + actual.terrain.heightmap(kind).map(|m| m.raw_data()), + expected.terrain.heightmap(kind).map(|m| m.raw_data()) + ); + } + assert_eq!( + actual.terrain.postprocessing(), + expected.terrain.postprocessing() + ); + assert_eq!( + actual.terrain.block_ticks().pack(0), + expected.terrain.block_ticks().pack(0) + ); + assert_eq!( + actual.terrain.fluid_ticks().pack(0), + expected.terrain.fluid_ticks().pack(0) + ); + assert_eq!(actual.block_entities, expected.block_entities); + assert_eq!(actual.entities, expected.entities); + assert_eq!(actual.structures(), expected.structures()); + } + assert!(!pipeline.identity_end_surface(ChunkPos::new(i32::MAX, 0))); + let old_rule = pipeline.rule.clone(); + pipeline.rule = MaterialRule::Block(registry.default_state("minecraft:stone").unwrap()); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + pipeline.rule = old_rule; + let old_fluid = pipeline.settings.default_fluid; + pipeline.settings.default_fluid = registry.default_state("minecraft:stone").unwrap(); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + pipeline.settings.default_fluid = old_fluid; + let old_source = std::mem::replace( + &mut pipeline.source, + ResolvedBiomeSource::Fixed(super::super::biome_source::FixedBiomeSource { + biome: "minecraft:the_end".into(), + }), + ); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + pipeline.source = old_source; + pipeline.aquifer = Some(std::array::from_fn(|_| { + pipeline.router.get(RouterField::Erosion).clone() + })); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + } #[test] fn uniform_surface_biomes_preserve_zoom_and_missing_corner_errors() { diff --git a/docs/media/command-suggestions/after.png b/docs/media/command-suggestions/after.png new file mode 100644 index 000000000..9c1a9cd4c Binary files /dev/null and b/docs/media/command-suggestions/after.png differ diff --git a/docs/media/command-suggestions/before.png b/docs/media/command-suggestions/before.png new file mode 100644 index 000000000..66c3925c4 Binary files /dev/null and b/docs/media/command-suggestions/before.png differ diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java index 0757bc2ef..e204d3cc0 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java @@ -27,7 +27,7 @@ import net.minecraft.world.phys.shapes.CollisionContext; /** * Native BlockItem placement-state selection (BlockPlaceContext resolution, * updatePlacementContext and getPlacementState) over generated neighbourhoods. - * Entities never obstruct; nothing is written to the world. + * Entity obstruction can be scripted; nothing is written to the world. */ public final class VanillaBlockPlacementOracle { static Object unsafe; @@ -67,6 +67,7 @@ public final class VanillaBlockPlacementOracle { static final class World extends net.minecraft.server.level.ServerLevel { Map cells; RandomSource random; + boolean obstructed; World() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } @@ -77,7 +78,7 @@ public final class VanillaBlockPlacementOracle { @Override public RandomSource getRandom() { return random; } @Override public int getMinY() { return -64; } @Override public int getHeight() { return 384; } - @Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return true; } + @Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return !obstructed; } @Override public boolean isUnobstructed(Entity entity) { return true; } @Override public void scheduleTick(BlockPos pos, Block block, int delay) { } @Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); } @@ -116,6 +117,7 @@ public final class VanillaBlockPlacementOracle { world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt())); } world.random = new LegacyRandomSource(f.get("seed").getAsLong()); + world.obstructed = f.has("obstructed") && f.get("obstructed").getAsBoolean(); var player = make(FakePlayer.class); player.world = world; player.yaw = f.get("yaw").getAsFloat(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java index 8034968a5..b2cdb3383 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java @@ -6,9 +6,14 @@ import java.io.PrintWriter; import net.minecraft.client.*; import net.minecraft.client.gui.Gui; import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.*; import net.minecraft.world.item.*; +import net.minecraft.world.item.component.SwingAnimation; import net.minecraft.world.level.GameType; /** Runs the real key handler through its drop loop; stops before item-use handling. */ @@ -41,16 +46,36 @@ public final class VanillaHeldDropOracle { } static final class Actor extends LocalPlayer { GameType mode; + int swings; Actor() { super(null, null, null, null, null, null, false, null, null); } @Override public GameType gameMode() { return mode; } @Override public boolean isUsingItem() { throw new Done(); } + @Override public boolean swing(InteractionHand hand, SwingAnimation animation, boolean sendPacket) { + if (hand != InteractionHand.MAIN_HAND || !animation.equals(SwingAnimation.DEFAULT) || sendPacket) + throw new AssertionError("unexpected drop swing"); + swings++; + return true; + } + } + static final class Connection extends ClientPacketListener { + int drops; + ServerboundPlayerActionPacket.Action expected; + Connection() { super(null, null, null); } + @Override public void send(Packet packet) { + if (packet instanceof ServerboundPlayerActionPacket action) { + if (action.getAction() != expected) throw new AssertionError("unexpected drop action"); + drops++; + } + } } static final class Controller extends MultiPlayerGameMode { int dropped; Controller() { super(null, null); } - // Controlled dispatch boundary: no networking, swings, statistics or item entities. + // Run vanilla's actual prediction, packet dispatch and conditional swing. @Override public void dropItem(LocalPlayer player, boolean all) { - dropped += player.getInventory().removeFromSelected(all).getCount(); + int before = player.getInventory().getSelectedItem().getCount(); + super.dropItem(player, all); + dropped += before - player.getInventory().getSelectedItem().getCount(); } } public static void main(String[] args) throws Exception { @@ -81,6 +106,9 @@ public final class VanillaHeldDropOracle { field(Player.class, "inventory").set(actor, inventory); field(Minecraft.class, "player").set(client, actor); var controller = make(Controller.class); + var connection = make(Connection.class); + field(MultiPlayerGameMode.class, "minecraft").set(controller, client); + field(MultiPlayerGameMode.class, "connection").set(controller, connection); field(Minecraft.class, "gameMode").set(client, controller); try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) { for (var mode : GameType.values()) for (boolean all : new boolean[]{false, true}) { @@ -91,6 +119,10 @@ public final class VanillaHeldDropOracle { inventory.setSelectedSlot(selected); inventory.setItem(selected, new ItemStack(Items.STONE, count)); controller.dropped = 0; + actor.swings = 0; + connection.drops = 0; + connection.expected = all ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS + : ServerboundPlayerActionPacket.Action.DROP_ITEM; // Two consecutive key presses also cover an emptied stack and repeated spectator drops. for (int press = 0; press < 2; press++) { ((Key) options.keyDrop).clicks = 1; @@ -100,7 +132,8 @@ public final class VanillaHeldDropOracle { } catch (InvocationTargetException e) { if (!(e.getCause() instanceof Done)) throw e; } - out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped); + out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped + + " " + actor.swings + " " + connection.drops); } } } diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py new file mode 100644 index 000000000..236b85c28 --- /dev/null +++ b/tests/test_remote_mining.py @@ -0,0 +1,149 @@ +"""Exercise the live remote_mining method with scripted world and packet sinks. + +Vanilla reference: MultiPlayerGameMode.startDestroyBlock/continueDestroyBlock. +The first_person parity harness separately checks consecutive instant breaks +against the pinned client; this fixture catches drift in the multiplayer path. +""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(shutil.which("rustc"), "requires Rust") +class RemoteMiningTests(unittest.TestCase): + def test_break_timing_and_packets(self): + source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text() + start = source.index(" fn remote_mining(") + end = source.index(" /// MultiPlayerGameMode.destroyBlock", start) + fixture = r''' +#![allow(dead_code)] +#[derive(Clone, Copy)] +struct Hit { pos: [i32; 3], face: u8 } +struct Mining { pos: [i32; 3], progress: f32, ticks: u32 } +#[derive(Default)] +struct Remote { destroy_delay: u32, destroying: Option<([i32; 3], u8, f32)> } +struct Ground { on_ground: bool } +struct Player { ground: Ground } +#[derive(Clone)] +struct Sounds { hit: String, volume: f32, pitch: f32 } +#[derive(Clone)] +struct Facts { hardness: f32, name: String, requires_tool: bool, sounds: Sounds } +struct Resources { facts: Facts, speed: f32 } +impl Resources { + fn facts(&self) -> &Self { self } + fn items(&self) -> &Self { self } + fn get(&self, _: u32) -> &Facts { &self.facts } + fn is_air(&self, state: u32) -> bool { state == 0 } + fn mining_speed(&self, _: Option<&()>, _: &str) -> f32 { self.speed } + fn correct_for_drops(&self, _: Option<&()>, _: &str) -> bool { true } +} +#[derive(Default)] +struct World { broken: Vec<[i32; 3]> } +impl World { + fn block(&self, x: i32, y: i32, z: i32) -> u32 { + u32::from(!self.broken.contains(&[x, y, z])) + } +} +struct Audio; +impl Audio { + fn play(&self, _: &str, _: Option<[f64; 3]>, _: f32, _: f32) {} +} +mod play { + #[derive(Debug, PartialEq)] + pub struct PlayerAction { + pub action: u8, pub pos: [i32; 3], pub direction: u8, pub sequence: i32, + } +} +enum S { PlayerAction(play::PlayerAction) } +fn face_direction(face: u8) -> u8 { face } +struct Game { + remote: Option, mining: Option, creative: bool, + world: World, res: Resources, player: Option, audio: Audio, + hit: Hit, sequence: i32, packets: Vec, +} +impl Game { + fn new(hardness: f32, speed: f32, creative: bool) -> Self { + Self { + remote: Some(Remote::default()), mining: None, creative, + world: World::default(), + res: Resources { facts: Facts { hardness, name: "block".into(), + requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed }, + player: Some(Player { ground: Ground { on_ground: true } }), audio: Audio, + hit: Hit { pos: [0, 64, 0], face: 1 }, sequence: 0, packets: vec![], + } + } + fn pick(&self) -> Option { Some(self.hit) } + fn held(&self) -> Option<&()> { None } + fn next_sequence(&mut self) -> i32 { self.sequence += 1; self.sequence } + fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); } + fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); } + fn crack_particle(&mut self, _: [i32; 3], _: u8, _: u32) {} +METHOD +} +fn main() { + // Zero-hardness blocks and a tool fast enough to break in one tick. + for (hardness, speed) in [(0.0, 1.0), (0.5, 15.0), (0.5, 30.0)] { + let mut game = Game::new(hardness, speed, false); + for tick in 0..8 { + game.hit.pos[0] = tick; + game.remote_mining(tick == 0); + assert_eq!(game.world.broken.len(), tick as usize + 1, + "instant break must happen every held tick"); + let remote = game.remote.as_ref().unwrap(); + assert_eq!(remote.destroy_delay, 0); + assert!(remote.destroying.is_none()); + assert!(game.mining.is_none()); + assert_eq!(game.packets[tick as usize], play::PlayerAction { + action: 0, pos: [tick, 64, 0], direction: 1, sequence: tick + 1, + }); + } + assert_eq!(game.packets.len(), 8, "instant breaks only send START"); + } + // Gradual breaking still sends STOP and waits five continuation ticks. + let mut game = Game::new(1.0, 15.0, false); + game.remote_mining(true); + assert!(game.world.broken.is_empty()); + game.remote_mining(false); + assert!(game.world.broken.is_empty()); + game.remote_mining(false); + assert_eq!(game.world.broken.len(), 1); + assert_eq!(game.packets.iter().map(|p| p.action).collect::>(), [0, 3]); + assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); + game.hit.pos[0] = 1; + for _ in 0..5 { + game.remote_mining(false); + assert_eq!(game.packets.len(), 2); + } + game.remote_mining(false); + assert_eq!(game.packets.len(), 3); + assert_eq!(game.packets[2].action, 0); + // Creative also keeps its five-tick delay, even for zero-hardness blocks. + let mut game = Game::new(0.0, 1.0, true); + game.remote_mining(true); + game.hit.pos[0] = 1; + assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); + for _ in 0..5 { + game.remote_mining(false); + assert_eq!(game.world.broken.len(), 1); + } + game.remote_mining(false); + assert_eq!(game.world.broken.len(), 2); + assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); +} +'''.replace("METHOD", source[start:end]) + with tempfile.TemporaryDirectory(prefix="remote-mining-") as directory: + path = Path(directory) + (path / "main.rs").write_text(fixture) + subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")], + check=True, capture_output=True, text=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 977d2e292..6f75b8a14 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -10,7 +10,8 @@ the options scenario reads and sets options.txt values by key; the events scenar states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport; the pick scenario middle-clicks slots (AbstractContainerScreen's cloning): a full stack in creative, from -the hotbar and from an item tab, and nothing in survival. +the hotbar and from an item tab, and nothing in survival; the suggestions scenario checks +slash-command Tab completion on single player's connected client after a fresh launch. python3 tools/agent_control_e2e.py # both modes python3 tools/agent_control_e2e.py --mode mcp # one of them @@ -45,6 +46,7 @@ LOG_KINDS = ['oak_log', 'birch_log', 'spruce_log', 'jungle_log', 'acacia_log', ' 'mangrove_log', 'cherry_log'] # Positional arguments of the commands the scenario uses, for the CLI. POSITIONAL = { + 'key': ['key', 'action'], 'goto': ['x', 'y', 'z'], 'break': ['x', 'y', 'z'], 'place': ['x', 'y', 'z'], 'block': ['x', 'y', 'z'], 'find_block': ['block', 'radius'], 'entities': ['radius', 'type'], 'click_slot': ['slot'], 'click_button': ['label'], 'type': ['text'], 'wait': ['ticks'], 'wait_ready': ['seconds'], @@ -522,8 +524,50 @@ def pick_scenario(d, out): return {'cloned': shown['item']} +def suggestions_scenario(d, out): + # Start from the title screen: single player's client joins through memory, + # without opening a server world and building its command registries. + d('click', id='singleplayer') + if 'game' not in widgets(d): + d('click', id='create-new-world') + d('type', field='name', replace=True, text='Suggestions') + d('click', id='game-mode') # survival -> hardcore -> creative (commands on) + d('click', id='game-mode') + d('type', field='seed', text='5') + d('click', id='world') + d('click', id='world-type') # superflat: this checks chat, without a spawn search + d('click', id='create-new-world') + d('wait_for', condition='loaded', timeout=400) + d('wait_ready', seconds=400) + + cases = [ + ('/giv', '/give'), + ('/fill ^', '/fill ^ ^'), + ('/give @s diamond_sw', '/give @s minecraft:diamond_sword'), + ('/setblock ~ ~ ~ diamond_blo', '/setblock ~ ~ ~ minecraft:diamond_block'), + ('/fill ~ ~ ~ ~1 ~1 ~1 diamond_blo', '/fill ~ ~ ~ ~1 ~1 ~1 minecraft:diamond_block'), + ('/setblock ~ ~ ~ oak_stairs[fa', '/setblock ~ ~ ~ oak_stairs[facing='), + ('/clear @s diamond_sw', '/clear @s minecraft:diamond_sword'), + ('/execute run give @s diamond_sw', '/execute run give @s minecraft:diamond_sword'), + ] + for text, expected in cases: + d('key', key='t', action='tap') + d('type', text=text) + if text == '/give @s diamond_sw': + shot = d('screenshot', path=str((out / f'{d.name}-suggestions.png').resolve())) + if '_image' in shot: + (out / f'{d.name}-suggestions.png').write_bytes(shot['_image']) + d('key', key='tab', action='tap') + actual = d('screen')['chat_input'] + assert actual == expected, (text, expected, actual) + d('key', key='esc', action='tap') + if d('screen')['screen'] == 'chat': # Escape first dismisses suggestions + d('key', key='esc', action='tap') + return {'completions': len(cases)} + + SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario, - 'consume': consume_scenario, 'pick': pick_scenario} + 'consume': consume_scenario, 'pick': pick_scenario, 'suggestions': suggestions_scenario} def run(mode, ctl, out, resources, which='survival'): diff --git a/tools/test_chat_screen_parity.py b/tools/test_chat_screen_parity.py index 52febd9f6..1447ebaa6 100644 --- a/tools/test_chat_screen_parity.py +++ b/tools/test_chat_screen_parity.py @@ -69,6 +69,16 @@ def cases(count): 'history': rng.sample(HISTORY, rng.randint(0, len(HISTORY))), 'autoSuggest': rng.random() < 0.85, 'chatOnly': rng.random() < 0.7, 'opacity': rng.choice([0.0, 0.5, 1.0]), 'actions': actions, 'mouse': list(mouse), 'blink': rng.choice([0, 100, 400, 650])}) + # Always exercise registry-backed suggestions and their replacement ranges, + # before and after Tab, including the redirect through execute's root. + for text in ['/give @s diamond_sw', '/setblock ~ ~ ~ sto', '/fill ~ ~ ~ ~1 ~1 ~1 sto', + '/setblock ~ ~ ~ oak_stairs[fa', '/clear @s diamond_sw', + '/execute run give @s diamond_sw', '/fill ']: + for keys in [[], ['tab'], ['tab', 'tab', 'shift+tab']]: + out.append({'width': 640, 'height': 360, 'initial': '', 'history': [], 'autoSuggest': True, + 'chatOnly': True, 'opacity': 0.5, 'mouse': [0, 0], 'blink': 0, + 'actions': [{'type': 'type', 'text': text}] + + [{'type': 'key', 'key': key} for key in keys]}) return out diff --git a/tools/test_firework_tooltip_parity.py b/tools/test_firework_tooltip_parity.py index e6cea9925..b3114c01a 100644 --- a/tools/test_firework_tooltip_parity.py +++ b/tools/test_firework_tooltip_parity.py @@ -67,6 +67,7 @@ if __name__ == '__main__': 'firework-tooltip-parity', 'VanillaFireworkTooltipOracle', 'firework_tooltip_fixture', cases, 'Firework rocket and star tooltip lines: flight duration, explosions (counted runs), colours, fade, trail, ' 'twinkle, defaults and tooltip_display', - sources=[lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs', + sources=[lab.ROOT / 'crates/horizon-client/src/enchant.rs', + lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs', lab.ROOT / 'crates/horizon-client/src/particles.rs'], expected_lines=COUNT) diff --git a/tools/test_first_person_parity.py b/tools/test_first_person_parity.py index d73262595..476d2cc52 100644 --- a/tools/test_first_person_parity.py +++ b/tools/test_first_person_parity.py @@ -69,6 +69,12 @@ def block_hit(pos, face=1): def scenarios(): stone = {TARGETS[0]: 'minecraft:stone', TARGETS[1]: 'minecraft:dirt', TARGETS[2]: 'minecraft:glass'} + # Consecutive instant survival breaks have no destroy delay. Cover both + # zero hardness and a shovel with haste reaching one-tick destroy progress. + for block, main, haste in [('minecraft:short_grass', None, None), + ('minecraft:dirt', ['minecraft:diamond_shovel', 1], 9)]: + steps = [step(block_hit(p), ac=int(i == 0), ad=True) for i, p in enumerate(TARGETS)] + yield case(steps + [step()] * 6, main=main, blocks={p: block for p in TARGETS}, haste=haste) for creative in (False, True): for main in ITEMS: # Hold attack on blocks until they break, then on the air behind. diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index c546c5987..842ad3d8a 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -2,10 +2,12 @@ """Compare selected-slot drops with Minecraft.handleKeybinds in all four game modes. The oracle invokes the unmodified native key handler, consuming real drop-key -clicks. Its controlled dropItem callback removes from the real player Inventory; -other keys are idle and execution stops at the following item-use boundary. +clicks, and MultiPlayerGameMode.dropItem's real prediction and swing dispatch. +Other keys are idle and execution stops at the following item-use boundary. Checks Q/Ctrl+Q, slots 0/8, empty/single/partial/full stacks and repeated drops. -Packet delivery, item entities, swing animation and statistics are outside scope. +Checks swing attempts and drop packet counts, including packets without swings +for empty slots. Packet delivery, animation ticks, item entities and statistics +are outside scope. """ import os import subprocess @@ -35,7 +37,7 @@ def main(): subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') - print(f'Held drop parity passed: {matched} selected-stack/drop-count snapshots match vanilla') + print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') if __name__ == '__main__': diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py index 423951942..23a68800c 100644 --- a/tools/test_level_place_parity.py +++ b/tools/test_level_place_parity.py @@ -68,6 +68,22 @@ def generate(resources, count, seed): return cases +def obstruction_cases(resources): + """Placement failures must not predict a hand swing. + + Exercise BlockItem.canPlace's entity-obstruction gate with the same + otherwise valid placements, including partial shapes and two-block items. + """ + facts = json.loads((resources / 'facts.json').read_text()) + states = {s[0]: i for i, s in reversed(list(enumerate(facts['states'])))} + stone = states['minecraft:stone'] + for item in ['minecraft:stone', 'minecraft:oak_slab', 'minecraft:oak_stairs', + 'minecraft:oak_door', 'minecraft:torch']: + for obstructed in [False, True]: + yield dict(seed=0, item=item, pos=[0, 0, 0], face=1, hit=[0.5, 1.0, 0.5], + yaw=0, pitch=45, sneak=False, cells=[[0, 0, 0, stone]], obstructed=obstructed) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', type=int, default=20000) @@ -77,7 +93,7 @@ def main(): resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] work = lab.LOCAL / 'level-place-parity' work.mkdir(parents=True, exist_ok=True) - cases = generate(resources, args.count, args.seed) + cases = list(obstruction_cases(resources)) + generate(resources, args.count, args.seed) (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases)) classes = work / 'classes' classes.mkdir(exist_ok=True)