From 2012f8baada33a3b6696af24fe61b2f516421f42 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:24:03 +0200 Subject: [PATCH 01/43] WIP: unfinished rendering-anim parity work, stopped for the night Uncommitted changes the agent had in progress when it was stopped; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- .../examples/block_entity_anim_fixture.rs | 342 ++++++++++ .../horizon-client/src/block_entity_anim.rs | 608 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + .../parity/VanillaBlockEntityAnimOracle.java | 264 ++++++++ tools/test_block_entity_anim_parity.py | 238 +++++++ 5 files changed, 1453 insertions(+) create mode 100644 crates/horizon-client/examples/block_entity_anim_fixture.rs create mode 100644 crates/horizon-client/src/block_entity_anim.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java create mode 100755 tools/test_block_entity_anim_parity.py diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/block_entity_anim_fixture.rs new file mode 100644 index 000000000..3013460f6 --- /dev/null +++ b/crates/horizon-client/examples/block_entity_anim_fixture.rs @@ -0,0 +1,342 @@ +//! Headless transport for the block-entity animation parity gate: replays each +//! scripted case (block, neighbourhood, entities, block events, game times) +//! through `horizon_client::block_entity_anim` and prints the same lines as +//! `VanillaBlockEntityAnimOracle`: the block entity's fields, the level calls +//! its tick made and the render state the renderer derives from `BlockAnim`. +#![forbid(unsafe_code)] +use horizon_client::{ + assets::Assets, + block_entity_anim::{ + Bell, BellEntity, BlockEntityAnims, Conduit, ConduitTarget, DIRECTIONS, PotWobble, + Shulker, ShulkerStatus, Skull, WobbleStyle, direction_index, + }, + blocks::{BlockFacts, Fluid}, + items::Items, +}; +use horizon_core::random::LegacyRandom; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::Value; +use std::{ + collections::HashMap, + fmt::Write as _, + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn f(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +fn d(v: f64) -> String { + format!("{:016x}", v.to_bits()) +} +fn bx(b: [f64; 6]) -> String { + b.map(d).join(" ") +} + +fn find_state(registry: &BlockRegistry, spec: &str) -> Option { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + let wanted: Vec<(&str, &str)> = props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .collect(); + let default = registry.state(registry.default_state(name)?)?.clone(); + (0..registry.len() as u32).find(|&id| { + registry.state(BlockStateId(id)).is_some_and(|s| { + s.name == name + && s.properties.iter().all(|(k, v)| { + wanted + .iter() + .find(|(wk, _)| wk == k) + .map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v) + }) + }) + }) +} + +fn prop<'a>(spec: &'a str, key: &str) -> Option<&'a str> { + let props = spec.split_once('[')?.1.trim_end_matches(']'); + props + .split(',') + .filter_map(|p| p.split_once('=')) + .find(|(k, _)| *k == key) + .map(|(_, v)| v) +} + +fn offset(key: &str) -> [i32; 3] { + let mut it = key.split(',').map(|v| v.parse::().unwrap_or(0)); + [ + it.next().unwrap_or(0), + it.next().unwrap_or(0), + it.next().unwrap_or(0), + ] +} + +fn mob(e: &Value) -> BellEntity { + let p = |i: usize| e["pos"][i].as_f64().unwrap_or(0.0); + BellEntity { + position: [p(0), p(1), p(2)], + alive: e["alive"].as_bool().unwrap_or(true) && !e["removed"].as_bool().unwrap_or(false), + raider: e["raider"].as_bool().unwrap_or(false), + } +} + +fn status(s: ShulkerStatus) -> &'static str { + match s { + ShulkerStatus::Closed => "CLOSED", + ShulkerStatus::Opening => "OPENING", + ShulkerStatus::Opened => "OPENED", + ShulkerStatus::Closing => "CLOSING", + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [root, inputs, output] = args.as_slice() else { + return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into()); + }; + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let tags = Items::tags_only(root)?; + let frames = tags + .block_tags + .get("minecraft:conduit_effect_block") + .cloned() + .unwrap_or_default(); + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let case: Value = serde_json::from_str(line)?; + writeln!(out, "case {}", case["name"].as_str().unwrap_or_default())?; + let block = case["block"].as_str().unwrap_or_default().to_owned(); + let int = |v: &Value| v.as_i64().unwrap_or(0) as i32; + let pos = [ + int(&case["pos"][0]), + int(&case["pos"][1]), + int(&case["pos"][2]), + ]; + // The neighbourhood as block states (conduits). + let mut blocks: HashMap<[i32; 3], String> = HashMap::new(); + blocks.insert(pos, block.clone()); + let mut place = |blocks: &mut HashMap<[i32; 3], String>, set: &Value| { + for (k, v) in set.as_object().into_iter().flatten() { + let o = offset(k); + blocks.insert( + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]], + v.as_str().unwrap_or_default().to_owned(), + ); + } + }; + place(&mut blocks, &case["world"]); + let entities: Vec = case["entities"] + .as_array() + .into_iter() + .flatten() + .map(mob) + .collect(); + let target = case.get("target").map(|t| { + let e = mob(t); + ConduitTarget { + position: e.position, + eye_y: e.position[1] + f64::from(t["eye"].as_f64().unwrap_or(0.0) as f32), + width: t["width"].as_f64().unwrap_or(0.0) as f32, + height: t["height"].as_f64().unwrap_or(0.0) as f32, + } + }); + let mut random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0)); + let name = block.split('[').next().unwrap_or_default().to_owned(); + let mut anims = BlockEntityAnims::default(); + let facing = prop(&block, "facing").and_then(direction_index).unwrap_or(1); + let mut text = String::new(); + for step in case["steps"].as_array().into_iter().flatten() { + let time = step["time"].as_i64().unwrap_or(0); + let partial = step["partial"].as_f64().unwrap_or(0.0) as f32; + let mut log = String::new(); + place(&mut blocks, &step["set"]); + let event = step["event"].as_array().map(|e| (int(&e[0]), int(&e[1]))); + text.clear(); + if name.ends_with("shulker_box") { + let s = anims.shulkers.entry(pos).or_insert_with(Shulker::default); + if let Some((a, b)) = event { + let handled = s.trigger_event(a, b); + let _ = write!(log, " event {handled}"); + } + let tick = s.tick(pos, facing); + for _ in 0..tick.neighbor_updates { + log.push_str(" neighbors"); + } + if let Some(b) = tick.push { + let _ = write!(log, " push {}", bx(b)); + } + let (count, st) = (s.open_count, s.status); + let a = anims.block_anim(pos, time, partial, Default::default()); + // ShulkerBoxRenderer: getProgress(partial). + let (progress, old) = a.shulker; + let render = old + partial * (progress - old); + let s = &anims.shulkers[&pos]; + let _ = write!( + text, + "{} {} {} {} render {}", + status(st), + count, + f(s.progress), + f(s.progress_old), + f(render) + ); + } else if name == "minecraft:bell" { + let b = anims.bells.entry(pos).or_insert_with(Bell::default); + if let Some((e0, e1)) = event { + let handled = b.trigger_event(e0, e1, time, || { + let inflated = [ + f64::from(pos[0]) - 48.0, + f64::from(pos[1]) - 48.0, + f64::from(pos[2]) - 48.0, + f64::from(pos[0]) + 1.0 + 48.0, + f64::from(pos[1]) + 1.0 + 48.0, + f64::from(pos[2]) + 1.0 + 48.0, + ]; + let _ = write!(log, " gather {}", bx(inflated)); + (0..entities.len() as u64) + .filter(|&i| { + let p = entities[i as usize].position; + (0..3).all(|a| p[a] >= inflated[a] && p[a] < inflated[a + 3]) + }) + .collect() + }); + let _ = write!(log, " event {handled}"); + } + if !step["noTick"].as_bool().unwrap_or(false) { + let tick = b.tick(pos, |h| entities.get(h as usize).copied()); + if tick.resonate { + log.push_str(" sound minecraft:block.bell.resonate"); + } + if let Some((particles, _)) = tick.ended { + for (p, color) in particles { + let _ = write!( + log, + " particle minecraft:entity_effect {color} {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(0.0), + d(0.0), + d(0.0) + ); + } + } + } + let b = &anims.bells[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + let dir = |d: Option<&str>| d.map_or("null".to_owned(), str::to_owned); + let _ = write!( + text, + "{} {} {} {} {} {} render {} {}", + b.ticks, + b.shaking, + dir(b.click_direction.map(|d| DIRECTIONS[usize::from(d)])), + b.resonating, + b.resonation_ticks, + b.last_ring_timestamp, + f(a.bell_ticks as f32 + partial), + dir(a.bell_shake) + ); + } else if name == "minecraft:conduit" { + let c = anims.conduits.entry(pos).or_insert_with(Conduit::default); + let state_of = |p: [i32; 3]| -> Option { + find_state(registry, blocks.get(&p).map_or("minecraft:air", String::as_str)) + }; + let is_water = + |p: [i32; 3]| state_of(p).is_some_and(|s| facts.get(s).fluid == Fluid::Water); + let is_frame = |p: [i32; 3]| { + let spec = blocks.get(&p).map_or("minecraft:air", String::as_str); + frames.contains(spec.split('[').next().unwrap_or_default()) + }; + let particles = c.client_tick(pos, time, is_water, is_frame, target, &mut random); + for (p, v) in particles { + let _ = write!( + log, + " particle minecraft:nautilus {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(v[0]), + d(v[1]), + d(v[2]) + ); + } + let c = &anims.conduits[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + // ConduitRenderer.extractRenderState as block_entity_render derives it. + let (ticks, active, hunting, raw) = a.conduit; + let rotation = (raw + if active { partial } else { 0.0 }) * -0.0375; + let _ = write!( + text, + "{} {} {} {} {} render {} {} {} {} {}", + c.tick_count, + c.is_active, + c.is_hunting, + f(c.active_rotation), + c.effect_blocks.len(), + active, + f(rotation), + f(ticks as f32 + partial), + ticks / 66 % 3, + hunting + ); + } else if name.ends_with("_head") || name.ends_with("_skull") { + let now = step["state"].as_str().unwrap_or(&block); + let s = anims.skulls.entry(pos).or_insert_with(Skull::default); + s.tick(prop(now, "powered") == Some("true")); + let s = anims.skulls[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + // block_entity_render: count + partial while animating. + let (animating, count) = a.skull; + let render = count as f32 + if animating { partial } else { 0.0 }; + let _ = write!( + text, + "{} {} render {}", + s.animating, + s.tick_count, + f(render) + ); + } else if name == "minecraft:decorated_pot" { + let w = anims.pots.entry(pos).or_insert_with(PotWobble::default); + if let Some((e0, e1)) = event { + let handled = w.trigger_event(e0, e1, time); + let _ = write!(log, " event {handled}"); + } + let w = anims.pots[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + let (style, progress) = match a.wobble { + Some((true, p)) => ("POSITIVE", p), + Some((false, p)) => ("null", p), + None => ("null", 0.0), + }; + let _ = write!( + text, + "{} {} render {} {}", + w.started_at, + match w.style { + Some(WobbleStyle::Positive) => "POSITIVE", + Some(WobbleStyle::Negative) => "NEGATIVE", + None => "null", + }, + f(progress), + style + ); + } else { + text = format!("unsupported {block}"); + } + writeln!(out, "{text} |{log}")?; + } + } + Ok(()) +} diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs new file mode 100644 index 000000000..fa74ac4d9 --- /dev/null +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -0,0 +1,608 @@ +//! Client-ticked block-entity animation state, as vanilla's block entities +//! keep it: `ShulkerBoxBlockEntity` (open count, animation status, progress), +//! `BellBlockEntity` (ring ticks, shake direction, resonation), +//! `ConduitBlockEntity.clientTick` (tick count, shape check, rotation, +//! hunting, nautilus particles), `SkullBlockEntity.animation` (powered dragon +//! and piglin heads) and `DecoratedPotBlockEntity` wobbles. +//! +//! [`BlockEntityAnims`] holds the state per position and turns it into the +//! renderer's [`BlockAnim`]. Its tick methods take what the level answers +//! (blocks, entities, game time) as closures, so the parity fixture can drive +//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`). +use crate::block_entity_render::BlockAnim; +use horizon_core::{ + geometry::trig::Mth, + random::{LegacyRandom, RandomSource}, +}; +use std::collections::HashMap; + +/// `Direction` names by `get3DDataValue`. +pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; + +fn step(direction: u8) -> [i32; 3] { + match direction { + 0 => [0, -1, 0], + 1 => [0, 1, 0], + 2 => [0, 0, -1], + 3 => [0, 0, 1], + 4 => [-1, 0, 0], + _ => [1, 0, 0], + } +} + +/// `Direction.from3DDataValue`: `BY_3D_DATA[Mth.abs(data % 6)]`. +pub fn from_3d_data_value(data: i32) -> u8 { + (data % 6).unsigned_abs() as u8 +} + +/// The 3D data value of a direction name. +pub fn direction_index(name: &str) -> Option { + DIRECTIONS.iter().position(|d| *d == name).map(|i| i as u8) +} + +/// `ShulkerBoxBlockEntity.AnimationStatus`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ShulkerStatus { + #[default] + Closed, + Opening, + Opened, + Closing, +} + +/// `ShulkerBoxBlockEntity` lid state. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Shulker { + pub open_count: i32, + pub status: ShulkerStatus, + pub progress: f32, + pub progress_old: f32, +} + +/// Side effects of one [`Shulker::tick`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ShulkerTick { + /// `doNeighborUpdates` calls (shape and neighbour updates around the box). + pub neighbor_updates: u32, + /// `moveCollidedEntities`: the swept lid box (min x, y, z, max x, y, z); + /// entities in it move out along the facing. + pub push: Option<[f64; 6]>, +} + +/// `Shulker.getProgressDeltaAabb(size, direction, from, to, position)`. +pub fn progress_delta_aabb( + size: f32, + direction: u8, + from: f32, + to: f32, + position: [f64; 3], +) -> [f64; 6] { + let size_d = f64::from(size); + let mut b = [ + -size_d * 0.5, + 0.0, + -size_d * 0.5, + size_d * 0.5, + size_d, + size_d * 0.5, + ]; + let max = f64::from(from.max(to)); + let min = f64::from(from.min(to)); + let s = step(direction); + for axis in 0..3 { + // expandTowards + let a = f64::from(s[axis]) * max * size_d; + if a < 0.0 { + b[axis] += a; + } else if a > 0.0 { + b[axis + 3] += a; + } + } + for axis in 0..3 { + // contract + let a = -f64::from(s[axis]) * (1.0 + min) * size_d; + if a < 0.0 { + b[axis] -= a; + } else if a > 0.0 { + b[axis + 3] -= a; + } + } + // new AABB keeps min <= max; then move to the position. + let mut out = [0.0; 6]; + for axis in 0..3 { + out[axis] = b[axis].min(b[axis + 3]) + position[axis]; + out[axis + 3] = b[axis].max(b[axis + 3]) + position[axis]; + } + out +} + +impl Shulker { + /// `triggerEvent(1, openCount)`. + pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool { + if b0 != 1 { + return false; + } + self.open_count = b1; + if b1 == 0 { + self.status = ShulkerStatus::Closing; + } + if b1 == 1 { + self.status = ShulkerStatus::Opening; + } + true + } + /// `startOpen`/`stopOpen` for a non-spectator user: the new open count to + /// send as block event 1, and whether this was the first opener (open) or + /// the last closer (close), which play the sound and game event. + pub fn start_open(&mut self) -> (i32, bool) { + if self.open_count < 0 { + self.open_count = 0; + } + self.open_count += 1; + (self.open_count, self.open_count == 1) + } + pub fn stop_open(&mut self) -> (i32, bool) { + self.open_count -= 1; + (self.open_count, self.open_count <= 0) + } + /// `updateAnimation` (`ShulkerBoxBlockEntity.tick`); `facing` is the + /// block's facing as a 3D data value. + pub fn tick(&mut self, pos: [i32; 3], facing: u8) -> ShulkerTick { + let mut out = ShulkerTick::default(); + self.progress_old = self.progress; + match self.status { + ShulkerStatus::Closed => self.progress = 0.0, + ShulkerStatus::Opening => { + self.progress += 0.1; + if self.progress_old == 0.0 { + out.neighbor_updates += 1; + } + if self.progress >= 1.0 { + self.status = ShulkerStatus::Opened; + self.progress = 1.0; + out.neighbor_updates += 1; + } + let bottom = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + out.push = Some(progress_delta_aabb( + 1.0, + facing, + self.progress_old, + self.progress, + bottom, + )); + } + ShulkerStatus::Opened => self.progress = 1.0, + ShulkerStatus::Closing => { + self.progress -= 0.1; + if self.progress_old == 1.0 { + out.neighbor_updates += 1; + } + if self.progress <= 0.0 { + self.status = ShulkerStatus::Closed; + self.progress = 0.0; + out.neighbor_updates += 1; + } + } + } + out + } + /// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`. + pub fn get_progress(&self, a: f32) -> f32 { + self.progress_old + a * (self.progress - self.progress_old) + } + /// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room + /// (`level.noCollision` of the half-block lid box, deflated by 1e-6). + pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] { + let bottom = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let mut b = progress_delta_aabb(1.0, facing, 0.0, 0.5, bottom); + for axis in 0..3 { + b[axis] += 1.0e-6; + b[axis + 3] -= 1.0e-6; + } + b + } +} + +/// What the bell's tick asks about an entity it gathered when rung. +#[derive(Clone, Copy, Debug)] +pub struct BellEntity { + pub position: [f64; 3], + /// `isAlive() && !isRemoved()`. + pub alive: bool, + /// In `EntityTypeTags.RAIDERS`. + pub raider: bool, +} + +/// `BellBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Bell { + pub ticks: i32, + pub shaking: bool, + /// `clickDirection` as a 3D data value. + pub click_direction: Option, + pub last_ring_timestamp: i64, + /// `nearbyEntities`: the living entities around the bell when it was last + /// gathered, as caller-defined handles. + pub nearby: Option>, + pub resonating: bool, + pub resonation_ticks: i32, +} + +/// Side effects of one [`Bell::tick`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BellTick { + /// Resonation started: `BELL_RESONATE` (played by the server). + pub resonate: bool, + /// Resonation ended (`ResonationEndAction`): the client's + /// `showBellParticles` entity-effect particles (position and colour) and + /// the server's `makeRaidersGlow` targets. + pub ended: Option<(Vec<([f64; 3], i32)>, Vec)>, +} + +fn closer_to_center_than(pos: [i32; 3], p: [f64; 3], distance: f64) -> bool { + let dx = f64::from(pos[0]) + 0.5 - p[0]; + let dy = f64::from(pos[1]) + 0.5 - p[1]; + let dz = f64::from(pos[2]) + 0.5 - p[2]; + dx * dx + dy * dy + dz * dz < distance * distance +} + +impl Bell { + /// `triggerEvent(1, direction)`. `gather` lists the living entities whose + /// position is inside the bell's block box inflated by 48 + /// (`updateEntities`, refreshed at most every 60 ticks). + pub fn trigger_event( + &mut self, + b0: i32, + b1: i32, + game_time: i64, + gather: impl FnOnce() -> Vec, + ) -> bool { + if b0 != 1 { + return false; + } + if game_time > self.last_ring_timestamp + 60 || self.nearby.is_none() { + self.last_ring_timestamp = game_time; + self.nearby = Some(gather()); + } + self.resonation_ticks = 0; + self.click_direction = Some(from_3d_data_value(b1)); + self.ticks = 0; + self.shaking = true; + true + } + /// `BellBlockEntity.tick` with the client's resonation end action. + pub fn tick(&mut self, pos: [i32; 3], entity: impl Fn(u64) -> Option) -> BellTick { + let mut out = BellTick::default(); + if self.shaking { + self.ticks += 1; + } + if self.ticks >= 50 { + self.shaking = false; + self.ticks = 0; + } + let nearby = self.nearby.clone().unwrap_or_default(); + let raider_in = |e: &BellEntity, distance: f64| { + e.alive && closer_to_center_than(pos, e.position, distance) && e.raider + }; + if self.ticks >= 5 + && self.resonation_ticks == 0 + && nearby + .iter() + .filter_map(|&h| entity(h)) + .any(|e| raider_in(&e, 32.0)) + { + self.resonating = true; + out.resonate = true; + } + if self.resonating { + if self.resonation_ticks < 40 { + self.resonation_ticks += 1; + } else { + // showBellParticles / makeRaidersGlow. + let mut color = 16_700_985; + let views: Vec<(u64, BellEntity)> = nearby + .iter() + .filter_map(|&h| Some((h, entity(h)?))) + .collect(); + let count = views + .iter() + .filter(|(_, e)| closer_to_center_than(pos, e.position, 48.0)) + .count() as i32; + let per = ((count - 21) / -2).clamp(3, 15); + let mut particles = Vec::new(); + let mut glow = Vec::new(); + for (h, e) in &views { + if !raider_in(e, 48.0) { + continue; + } + glow.push(*h); + let (bx, bz) = (f64::from(pos[0]), f64::from(pos[2])); + let dist = ((e.position[0] - bx) * (e.position[0] - bx) + + (e.position[2] - bz) * (e.position[2] - bz)) + .sqrt(); + let x3 = bx + f64::from(0.5f32) + 1.0 / dist * (e.position[0] - bx); + let z3 = bz + f64::from(0.5f32) + 1.0 / dist * (e.position[2] - bz); + for _ in 0..per { + color += 5; + particles.push(([x3, f64::from(pos[1]) + 0.5, z3], color)); + } + } + out.ended = Some((particles, glow)); + self.resonating = false; + } + } + out + } +} + +/// The conduit's `destroyTarget` as the client sees it. +#[derive(Clone, Copy, Debug)] +pub struct ConduitTarget { + pub position: [f64; 3], + pub eye_y: f64, + pub width: f32, + pub height: f32, +} + +/// `ConduitBlockEntity` (client side). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Conduit { + pub tick_count: i32, + pub active_rotation: f32, + pub is_active: bool, + pub is_hunting: bool, + pub effect_blocks: Vec<[i32; 3]>, +} + +/// One nautilus particle: position and velocity. +pub type Particle = ([f64; 3], [f64; 3]); + +impl Conduit { + /// `updateShape`: water all around, then the frame blocks + /// (`BlockTags.CONDUIT_EFFECT_BLOCK`) in the three 5x5 rings. + fn update_shape( + &mut self, + pos: [i32; 3], + is_water: &impl Fn([i32; 3]) -> bool, + is_frame: &impl Fn([i32; 3]) -> bool, + ) -> bool { + self.effect_blocks.clear(); + for ox in -1..=1 { + for oy in -1..=1 { + for oz in -1..=1 { + if !is_water([pos[0] + ox, pos[1] + oy, pos[2] + oz]) { + return false; + } + } + } + } + for ox in -2i32..=2 { + for oy in -2i32..=2 { + for oz in -2i32..=2 { + let (ax, ay, az) = (ox.abs(), oy.abs(), oz.abs()); + if (ax > 1 || ay > 1 || az > 1) + && (ox == 0 && (ay == 2 || az == 2) + || oy == 0 && (ax == 2 || az == 2) + || oz == 0 && (ax == 2 || ay == 2)) + { + let p = [pos[0] + ox, pos[1] + oy, pos[2] + oz]; + if is_frame(p) { + self.effect_blocks.push(p); + } + } + } + } + } + self.effect_blocks.len() >= 16 + } + /// `ConduitBlockEntity.clientTick`: returns the nautilus particles of + /// `animationTick`, drawn from the client level's random. + pub fn client_tick( + &mut self, + pos: [i32; 3], + game_time: i64, + is_water: impl Fn([i32; 3]) -> bool, + is_frame: impl Fn([i32; 3]) -> bool, + target: Option, + random: &mut impl RandomSource, + ) -> Vec { + self.tick_count += 1; + if game_time % 40 == 0 { + self.is_active = self.update_shape(pos, &is_water, &is_frame); + self.is_hunting = self.effect_blocks.len() >= 42; + } + let particles = self.animation_tick(pos, target, random); + if self.is_active { + self.active_rotation += 1.0; + } + particles + } + fn animation_tick( + &self, + pos: [i32; 3], + target: Option, + random: &mut impl RandomSource, + ) -> Vec { + let mut out = Vec::new(); + let hh = f64::from(((self.tick_count + 35) as f32 * 0.1).msin() / 2.0 + 0.5); + let hh = (hh * hh + hh) * f64::from(0.3f32); + let end = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.5 + hh, + f64::from(pos[2]) + 0.5, + ]; + for p in &self.effect_blocks { + if random.next_int_bound(50).unwrap_or(1) == 0 { + let dx = -0.5 + random.next_float() + (p[0] - pos[0]) as f32; + let dy = -2.0 + random.next_float() + (p[1] - pos[1]) as f32; + let dz = -0.5 + random.next_float() + (p[2] - pos[2]) as f32; + out.push((end, [f64::from(dx), f64::from(dy), f64::from(dz)])); + } + } + if let Some(t) = target { + let randx = (-0.5 + random.next_float()) * (3.0 + t.width); + let randy = -1.0 + random.next_float() * t.height; + let randz = (-0.5 + random.next_float()) * (3.0 + t.width); + out.push(( + [t.position[0], t.eye_y, t.position[2]], + [f64::from(randx), f64::from(randy), f64::from(randz)], + )); + } + out + } +} + +/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Skull { + pub animating: bool, + pub tick_count: i32, +} +impl Skull { + /// `SkullBlockEntity.animation`. + pub fn tick(&mut self, powered: bool) { + if powered { + self.animating = true; + self.tick_count += 1; + } else { + self.animating = false; + } + } + /// `getAnimation(a)`. + pub fn get_animation(&self, a: f32) -> f32 { + if self.animating { + self.tick_count as f32 + a + } else { + self.tick_count as f32 + } + } +} + +/// `DecoratedPotBlockEntity.WobbleStyle`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WobbleStyle { + Positive, + Negative, +} +impl WobbleStyle { + pub fn duration(self) -> i32 { + match self { + Self::Positive => 7, + Self::Negative => 10, + } + } +} + +/// `DecoratedPotBlockEntity` wobble fields. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PotWobble { + pub started_at: i64, + pub style: Option, +} +impl PotWobble { + /// `triggerEvent(1, style)`. + pub fn trigger_event(&mut self, event: i32, data: i32, game_time: i64) -> bool { + if event == 1 && (0..2).contains(&data) { + self.started_at = game_time; + self.style = Some(if data == 0 { + WobbleStyle::Positive + } else { + WobbleStyle::Negative + }); + true + } else { + false + } + } + /// `DecoratedPotRenderer.extractRenderState`'s `wobbleProgress`. + pub fn progress(&self, game_time: i64, partial: f32) -> f32 { + match self.style { + Some(style) => { + ((game_time - self.started_at) as f32 + partial) / style.duration() as f32 + } + None => 0.0, + } + } +} + +/// The animated block entities of a level, by position. +#[derive(Clone, Debug)] +pub struct BlockEntityAnims { + pub shulkers: HashMap<[i32; 3], Shulker>, + pub bells: HashMap<[i32; 3], Bell>, + pub conduits: HashMap<[i32; 3], Conduit>, + pub skulls: HashMap<[i32; 3], Skull>, + pub pots: HashMap<[i32; 3], PotWobble>, + /// The client level's random (conduit particles). + pub random: LegacyRandom, +} +impl Default for BlockEntityAnims { + fn default() -> Self { + Self { + shulkers: HashMap::new(), + bells: HashMap::new(), + conduits: HashMap::new(), + skulls: HashMap::new(), + pots: HashMap::new(), + random: LegacyRandom::new(0x6c6576656c), + } + } +} +impl BlockEntityAnims { + /// Drops the state of positions whose block entity is gone. + pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) { + self.shulkers.retain(|p, _| keep(*p)); + self.bells.retain(|p, _| keep(*p)); + self.conduits.retain(|p, _| keep(*p)); + self.skulls.retain(|p, _| keep(*p)); + self.pots.retain(|p, _| keep(*p)); + } + /// The renderer's view of the block entity at `pos`; `sherds` are the + /// pot's decorations (back, left, right, front), when it is a pot. + pub fn block_anim( + &self, + pos: [i32; 3], + game_time: i64, + partial: f32, + sherds: [Option; 4], + ) -> BlockAnim { + let mut anim = BlockAnim { + sherds, + ..BlockAnim::default() + }; + if let Some(s) = self.shulkers.get(&pos) { + anim.shulker = (s.progress, s.progress_old); + } + if let Some(b) = self.bells.get(&pos) { + anim.bell_ticks = b.ticks; + anim.bell_shake = b + .shaking + .then_some(b.click_direction) + .flatten() + .map(|d| DIRECTIONS[usize::from(d)]); + } + if let Some(c) = self.conduits.get(&pos) { + anim.conduit = (c.tick_count, c.is_active, c.is_hunting, c.active_rotation); + } + if let Some(s) = self.skulls.get(&pos) { + anim.skull = (s.animating, s.tick_count); + } + if let Some(w) = self.pots.get(&pos) + && w.style.is_some() + { + // extractRenderState never copies lastWobbleStyle into the render + // state, so DecoratedPotRenderer.submit always takes the + // non-POSITIVE branch (with the style's own duration). + anim.wobble = Some((false, w.progress(game_time, partial))); + } + anim + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 8b2ed8ade..286c7d148 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -9,6 +9,7 @@ pub mod attribute_updates; pub mod audio; pub mod banner; pub mod biome; +pub mod block_entity_anim; pub mod block_entity_nbt; pub mod block_entity_render; pub mod block_transform; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java new file mode 100644 index 000000000..f8ab143c3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java @@ -0,0 +1,264 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.client.renderer.blockentity.*; +import net.minecraft.client.renderer.blockentity.state.*; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.*; +import net.minecraft.core.particles.ColorParticleOption; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.*; + +/** + * Original oracle for the client-ticked animation state of shulker boxes, + * bells, conduits, skulls and decorated pots. Each case builds the real + * vanilla block entity on a stand-in client level (scripted blocks, entities, + * game time and a seeded LegacyRandomSource), then per step applies the + * scripted block event (triggerEvent), runs the block entity's own client + * ticker (ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick, + * ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none) + * and runs the real renderer's extractRenderState at the step's partial tick. + * It prints the block entity's fields, the level calls the tick made + * (neighbour updates, entity queries, sounds, particles) and the render state. + * + * Usage: VanillaBlockEntityAnimOracle inputs.jsonl output.txt + */ +public final class VanillaBlockEntityAnimOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + @SuppressWarnings("unchecked") + static T make(Class type) throws Exception { return (T) allocate.invoke(unsafe, type); } + + static void put(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + long offset = (long) objectFieldOffset.invoke(unsafe, f); + putObject.invoke(unsafe, target, offset, value); + } + + static Field field(Class owner, String name) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static String f(float v) { return String.format("%08x", Float.floatToRawIntBits(v)); } + static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); } + static String box(AABB b) { return d(b.minX) + " " + d(b.minY) + " " + d(b.minZ) + " " + d(b.maxX) + " " + d(b.maxY) + " " + d(b.maxZ); } + + static BlockState parse(String s) throws Exception { + return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, s, false).blockState(); + } + + /** A living entity the case places: a Pillager whose type field says raider or not. */ + static final class Mob extends net.minecraft.world.entity.monster.illager.Pillager { + boolean living; + Mob() { super(null, null); } + @Override public boolean isAlive() { return !this.isRemoved() && this.living; } + } + + /** The stand-in client level. */ + static final class World extends Level { + World() { super(null, null, null, null, false, false, 0L, 0); } + long time; + Map blocks = new HashMap<>(); + List mobs = new ArrayList<>(); + RandomSource random; + StringBuilder log = new StringBuilder(); + + @Override public long getGameTime() { return time; } + @Override public boolean isClientSide() { return true; } + @Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); } + @Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); } + @Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; } + @Override public RandomSource getRandom() { return random; } + @Override public void updateNeighborsAt(BlockPos p, Block block) { log.append(" neighbors"); } + @Override public void neighborShapeChanged(Direction dir, BlockPos p, BlockPos from, BlockState state, int flags, int limit) {} + @Override public List getEntities(Entity except, AABB bb) { log.append(" push ").append(box(bb)); return List.of(); } + @SuppressWarnings("unchecked") + @Override public List getEntitiesOfClass(Class type, AABB bb, Predicate selector) { + log.append(" gather ").append(box(bb)); + List out = new ArrayList<>(); + for (Mob m : mobs) if (type.isInstance(m) && bb.contains(m.position())) out.add((T) m); + return out; + } + @Override public void playSound(Entity except, BlockPos p, SoundEvent s, SoundSource source, float volume, float pitch) { + log.append(" sound ").append(BuiltInRegistries.SOUND_EVENT.getKey(s)); + } + @Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) { + log.append(" particle ").append(BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType())); + if (o instanceof ColorParticleOption c) { + try { log.append(" ").append(field(ColorParticleOption.class, "color").getInt(c)); } catch (Exception e) { throw new RuntimeException(e); } + } + log.append(" ").append(d(x)).append(" ").append(d(y)).append(" ").append(d(z)) + .append(" ").append(d(xd)).append(" ").append(d(yd)).append(" ").append(d(zd)); + } +@Override public net.minecraft.world.clock.ClockManager clockManager(){throw new UnsupportedOperationException();} +@Override public void destroyBlockProgress(int p0,net.minecraft.core.BlockPos p1,int p2){throw new UnsupportedOperationException();} +@Override public java.util.Collection dragonParts(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){throw new UnsupportedOperationException();} +@Override public void explode(net.minecraft.world.entity.Entity p0,net.minecraft.world.damagesource.DamageSource p1,net.minecraft.world.level.ExplosionDamageCalculator p2,double p3,double p4,double p5,float p6,boolean p7,net.minecraft.world.level.Level.ExplosionInteraction p8,net.minecraft.core.particles.ParticleOptions p9,net.minecraft.core.particles.ParticleOptions p10,net.minecraft.util.random.WeightedList p11,net.minecraft.core.Holder p12){throw new UnsupportedOperationException();} +@Override public void gameEvent(net.minecraft.core.Holder p0,net.minecraft.world.phys.Vec3 p1,net.minecraft.world.level.gameevent.GameEvent.Context p2){throw new UnsupportedOperationException();} +@Override public java.lang.String gatherChunkSourceStats(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.ticks.LevelTickAccess getBlockTicks(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.chunk.ChunkSource getChunkSource(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.entity.LevelEntityGetter getEntities(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.entity.Entity getEntity(int p0){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.ticks.LevelTickAccess getFluidTicks(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId p0){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.storage.LevelData.RespawnData getRespawnData(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.scores.Scoreboard getScoreboard(){throw new UnsupportedOperationException();} +@Override public int getSeaLevel(){throw new UnsupportedOperationException();} +@Override public net.minecraft.core.Holder getUncachedNoiseBiome(int p0,int p1,int p2){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder(){throw new UnsupportedOperationException();} +@Override public void levelEvent(net.minecraft.world.entity.Entity p0,int p1,net.minecraft.core.BlockPos p2,int p3){throw new UnsupportedOperationException();} +@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,net.minecraft.world.entity.Entity p1,net.minecraft.core.Holder p2,net.minecraft.sounds.SoundSource p3,float p4,float p5,long p6){throw new UnsupportedOperationException();} +@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,double p1,double p2,double p3,net.minecraft.core.Holder p4,net.minecraft.sounds.SoundSource p5,float p6,float p7,long p8){throw new UnsupportedOperationException();} +@Override public java.util.List players(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.item.crafting.RecipeAccess recipeAccess(){throw new UnsupportedOperationException();} +@Override public void sendBlockUpdated(net.minecraft.core.BlockPos p0,net.minecraft.world.level.block.state.BlockState p1,net.minecraft.world.level.block.state.BlockState p2,int p3){throw new UnsupportedOperationException();} +@Override public void setRespawnData(net.minecraft.world.level.storage.LevelData.RespawnData p0){throw new UnsupportedOperationException();} + } + + static Mob mob(JsonObject e, World world) throws Exception { + Mob m = make(Mob.class); + m.living = !e.has("alive") || e.get("alive").getAsBoolean(); + put(m, Entity.class, "type", e.has("raider") && e.get("raider").getAsBoolean() ? EntityType.PILLAGER : EntityType.COW); + var p = e.getAsJsonArray("pos"); + put(m, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble())); + if (e.has("removed") && e.get("removed").getAsBoolean()) put(m, Entity.class, "removalReason", Entity.RemovalReason.KILLED); + if (e.has("width")) { + put(m, Entity.class, "dimensions", EntityDimensions.scalable(e.get("width").getAsFloat(), e.get("height").getAsFloat())); + Field eye = field(Entity.class, "eyeHeight"); + eye.setFloat(m, e.get("eye").getAsFloat()); + } + return m; + } + + static String run(JsonObject c) throws Exception { + World world = make(World.class); + world.blocks = new HashMap<>(); + world.mobs = new ArrayList<>(); + world.log = new StringBuilder(); + world.random = RandomSource.create(c.has("seed") ? c.get("seed").getAsLong() : 0L); + var pa = c.getAsJsonArray("pos"); + BlockPos pos = new BlockPos(pa.get(0).getAsInt(), pa.get(1).getAsInt(), pa.get(2).getAsInt()); + BlockState state = parse(c.get("block").getAsString()); + world.blocks.put(pos, state); + if (c.has("world")) { + for (var e : c.getAsJsonObject("world").entrySet()) { + String[] xyz = e.getKey().split(","); + world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString())); + } + } + if (c.has("entities")) for (var e : c.getAsJsonArray("entities")) world.mobs.add(mob(e.getAsJsonObject(), world)); + var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state); + be.setLevel(world); + if (c.has("target") && be instanceof ConduitBlockEntity) { + put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world))); + } + StringBuilder out = new StringBuilder(); + for (var stepElement : c.getAsJsonArray("steps")) { + var step = stepElement.getAsJsonObject(); + world.time = step.get("time").getAsLong(); + world.log.setLength(0); + if (step.has("set")) { + for (var e : step.getAsJsonObject("set").entrySet()) { + String[] xyz = e.getKey().split(","); + world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString())); + } + } + if (step.has("event")) { + var ev = step.getAsJsonArray("event"); + boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt()); + world.log.append(" event ").append(handled); + } + float partial = step.get("partial").getAsFloat(); + String fields; + if (be instanceof ShulkerBoxBlockEntity s) { + ShulkerBoxBlockEntity.tick(world, pos, state, s); + var r = make(ShulkerBoxRenderer.class).createRenderState(); + make(ShulkerBoxRenderer.class).extractRenderState(s, r, partial, Vec3.ZERO, null); + fields = s.getAnimationStatus() + " " + field(ShulkerBoxBlockEntity.class, "openCount").getInt(s) + + " " + f(field(ShulkerBoxBlockEntity.class, "progress").getFloat(s)) + + " " + f(field(ShulkerBoxBlockEntity.class, "progressOld").getFloat(s)) + + " render " + f(r.progress); + } else if (be instanceof BellBlockEntity b) { + if (!step.has("noTick")) BellBlockEntity.clientTick(world, pos, state, b); + var r = make(BellRenderer.class).createRenderState(); + make(BellRenderer.class).extractRenderState(b, r, partial, Vec3.ZERO, null); + fields = b.ticks + " " + b.shaking + " " + b.clickDirection + + " " + field(BellBlockEntity.class, "resonating").getBoolean(b) + + " " + field(BellBlockEntity.class, "resonationTicks").getInt(b) + + " " + field(BellBlockEntity.class, "lastRingTimestamp").getLong(b) + + " render " + f(r.ticks) + " " + r.shakeDirection; + } else if (be instanceof ConduitBlockEntity k) { + ConduitBlockEntity.clientTick(world, pos, state, k); + var r = make(ConduitRenderer.class).createRenderState(); + make(ConduitRenderer.class).extractRenderState(k, r, partial, Vec3.ZERO, null); + @SuppressWarnings("unchecked") + var effect = (List) field(ConduitBlockEntity.class, "effectBlocks").get(k); + fields = k.tickCount + " " + k.isActive() + " " + k.isHunting() + + " " + f(field(ConduitBlockEntity.class, "activeRotation").getFloat(k)) + " " + effect.size() + + " render " + r.isActive + " " + f(r.activeRotation) + " " + f(r.animTime) + " " + r.animationPhase + " " + r.isHunting; + } else if (be instanceof SkullBlockEntity k) { + BlockState now = step.has("state") ? parse(step.get("state").getAsString()) : state; + SkullBlockEntity.animation(world, pos, now, k); + fields = field(SkullBlockEntity.class, "isAnimating").getBoolean(k) + + " " + field(SkullBlockEntity.class, "animationTickCount").getInt(k) + + " render " + f(k.getAnimation(partial)); + } else if (be instanceof DecoratedPotBlockEntity p) { + var r = make(DecoratedPotRenderer.class).createRenderState(); + make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null); + fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle + + " render " + f(r.wobbleProgress) + " " + r.wobbleStyle; + } else { + throw new IllegalArgumentException("no animation for " + be); + } + out.append(fields).append(" |").append(world.log).append('\n'); + } + return out.toString(); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var allocator = Class.forName("sun.misc.Unsafe"); + var theUnsafe = allocator.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + unsafe = theUnsafe.get(null); + allocate = allocator.getMethod("allocateInstance", Class.class); + putObject = allocator.getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = allocator.getMethod("objectFieldOffset", Field.class); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + String result; + try { + result = run(c); + } catch (Throwable t) { + result = "error " + t + "\n"; + } + out.print("case " + c.get("name").getAsString() + "\n" + result); + } + } + } +} diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py new file mode 100755 index 000000000..ac7174108 --- /dev/null +++ b/tools/test_block_entity_anim_parity.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Compare client-ticked block-entity animation with the vanilla 26.3 block entities. + +The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla +block entity (shulker box, bell, conduit, dragon/piglin head, decorated pot) +on a stand-in client level, then per scripted step applies the block event +(triggerEvent), runs the entity's own client ticker and the renderer's +extractRenderState, printing the fields, the level calls the tick made +(neighbour updates, entity pushes/queries, sounds, particles) and the render +state. `examples/block_entity_anim_fixture` replays the steps through +`horizon_client::block_entity_anim` and derives the render state from the +`BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits). + + test_block_entity_anim_parity.py [--filter SUBSTRING] [--detail N] +""" +import argparse +import json +import os +import random +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +HORIZONTAL = ['north', 'south', 'west', 'east'] +ALL = ['down', 'up'] + HORIZONTAL +FRAME = ['minecraft:prismarine', 'minecraft:prismarine_bricks', 'minecraft:sea_lantern', 'minecraft:dark_prismarine'] +WATERY = ['minecraft:water', 'minecraft:water[level=3]', 'minecraft:bubble_column', 'minecraft:seagrass', + 'minecraft:kelp_plant', 'minecraft:oak_slab[waterlogged=true]', 'minecraft:oak_stairs[waterlogged=true]'] +DRY = ['minecraft:air', 'minecraft:stone', 'minecraft:lava', 'minecraft:oak_slab', 'minecraft:ice'] + + +def frame_offsets(): + out = [] + for ox in range(-2, 3): + for oy in range(-2, 3): + for oz in range(-2, 3): + ax, ay, az = abs(ox), abs(oy), abs(oz) + if (ax > 1 or ay > 1 or az > 1) and (ox == 0 and (ay == 2 or az == 2) or oy == 0 and (ax == 2 or az == 2) + or oz == 0 and (ax == 2 or ay == 2)): + out.append((ox, oy, oz)) + return out + + +def cases(): + rng = random.Random(0x414e494d) + out = [] + + def pos(): + return [rng.randint(-3000, 3000), rng.randint(-60, 300), rng.randint(-3000, 3000)] + + def add(kind, block, steps, **extra): + case = {'name': f'{kind}-{len(out)}', 'block': block, 'pos': pos(), 'steps': steps} + case.update(extra) + out.append(case) + + def times(n, start=None, gaps=(1,)): + t = rng.randint(-100, 10 ** 7) if start is None else start + result = [] + for _ in range(n): + result.append(t) + t += rng.choice(gaps) + return result + + # Shulker boxes: players open and close (open counts from startOpen/stopOpen), other events ignored. + for i in range(48): + color = rng.choice(['', 'white_', 'purple_', 'black_']) + block = f'minecraft:{color}shulker_box[facing={rng.choice(ALL)}]' + steps, count = [], 0 + for t in times(rng.randint(20, 70)): + step = {'time': t, 'partial': round(rng.random(), 4)} + r = rng.random() + if r < 0.12: + count = max(count, 0) + 1 + step['event'] = [1, count] + elif r < 0.22: + count -= 1 + step['event'] = [1, count] + elif r < 0.25: + step['event'] = [rng.choice([0, 2, 1]), rng.randint(-2, 3)] + steps.append(step) + add('shulker', block, steps) + + # Bells: rings from any side (and odd data values), raiders and other mobs nearby. + for i in range(40): + attach = rng.choice(['floor', 'ceiling', 'single_wall', 'double_wall']) + block = f'minecraft:bell[attachment={attach},facing={rng.choice(HORIZONTAL)}]' + p = pos() + entities = [] + for _ in range(rng.choice([0, 1, 2, 5, 12, 25])): + spread = rng.choice([10, 33, 50, 70]) + entities.append({'pos': [p[k] + 0.5 + rng.uniform(-spread, spread) for k in range(3)], + 'raider': rng.random() < 0.5, 'alive': rng.random() < 0.85, 'removed': rng.random() < 0.08}) + steps = [] + start = rng.randint(-50, 10 ** 6) + for k, t in enumerate(times(rng.randint(60, 180), start)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if (k == 2 or rng.random() < 0.05) and k < 150: + step['event'] = [1 if rng.random() < 0.93 else 2, rng.choice([0, 1, 2, 3, 4, 5, 2, 3, 4, 5, 7, -3, 11])] + steps.append(step) + case = {'name': f'bell-{len(out)}', 'block': block, 'pos': p, 'steps': steps, 'entities': entities} + out.append(case) + + # Conduits: water around, prismarine frames of various sizes, frames changing over time. + rings = frame_offsets() + for i in range(36): + world = {} + water = rng.random() + for ox in range(-1, 2): + for oy in range(-1, 2): + for oz in range(-1, 2): + if (ox, oy, oz) != (0, 0, 0): + world[f'{ox},{oy},{oz}'] = rng.choice(WATERY) if rng.random() < 0.97 or water < 0.5 else rng.choice(DRY) + size = rng.choice([0, 10, 15, 16, 20, 30, 41, 42, 42]) + for o in rng.sample(rings, size): + world['%d,%d,%d' % o] = rng.choice(FRAME) + steps = [] + for t in times(rng.randint(60, 140), gaps=(1, 1, 1, 2, 7)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.04: + o = rng.choice(rings) + step['set'] = {'%d,%d,%d' % o: rng.choice(FRAME + DRY)} + steps.append(step) + waterlogged = 'true' if rng.random() < 0.9 else 'false' + extra = {'world': world, 'seed': rng.randint(0, 2 ** 40)} + if rng.random() < 0.3: + extra['target'] = {'pos': [rng.uniform(-8, 8) for _ in range(3)], 'width': round(rng.uniform(0.3, 2), 3), + 'height': round(rng.uniform(0.5, 3), 3), 'eye': round(rng.uniform(0.2, 2.5), 3)} + add('conduit', f'minecraft:conduit[waterlogged={waterlogged}]', steps, **extra) + + # Dragon and piglin heads powered on and off. + for i in range(24): + head = rng.choice(['dragon', 'piglin']) + wall = rng.random() < 0.5 + prop = f'facing={rng.choice(HORIZONTAL)}' if wall else f'rotation={rng.randint(0, 15)}' + name = f'minecraft:{head}_wall_head' if wall else f'minecraft:{head}_head' + powered = rng.random() < 0.5 + steps = [] + for t in times(rng.randint(20, 90)): + if rng.random() < 0.1: + powered = not powered + steps.append({'time': t, 'partial': round(rng.random(), 4), + 'state': f'{name}[{prop},powered={str(powered).lower()}]'}) + add('skull', f'{name}[{prop},powered=false]', steps) + + # Decorated pots wobbling (insert: POSITIVE, fail: NEGATIVE) and invalid events. + for i in range(24): + steps = [] + for t in times(rng.randint(20, 60), gaps=(0, 1, 1, 1, 3)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.15: + step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])] + steps.append(step) + add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--filter', default='') + parser.add_argument('--detail', type=int, default=3) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-block-entity-anim-parity' + build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + chosen = [c for c in cases() if args.filter in c['name']] + inputs = build / 'inputs.jsonl' + inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]) + sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, + *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java') + run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle', + inputs, build / 'vanilla.txt'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_anim_fixture', '--', + resources, inputs, build / 'rust.txt'], 'rust') + + def split(path): + result, current = {}, None + for line in path.read_text().splitlines(): + if line.startswith('case '): + current = line[5:] + result[current] = [] + else: + result[current].append(line) + return result + vanilla, rust = split(build / 'vanilla.txt'), split(build / 'rust.txt') + kinds, failures, errors, steps = {}, {}, {}, 0 + for case in chosen: + name = case['name'] + kind = name.split('-')[0] + v, r = vanilla.get(name, []), rust.get(name, []) + total = kinds.setdefault(kind, [0, 0]) + total[1] += 1 + if v and v[0].startswith('error'): + errors.setdefault(kind, v[0]) + continue + steps += len(v) + bad = next((i for i, (a, b) in enumerate(zip(v, r)) if a != b), None) + if bad is None and len(v) != len(r): + bad = min(len(v), len(r)) + if bad is None: + total[0] += 1 + else: + failures.setdefault(kind, []).append((case, bad, v[bad] if bad < len(v) else None, r[bad] if bad < len(r) else None)) + for kind, error in sorted(errors.items()): + print(f'ORACLE ERROR {kind}: {error[:600]}') + for kind, items in sorted(failures.items()): + print(f'MISMATCH {kind}: {len(items)} cases') + for case, step, a, b in items[:args.detail]: + print(f' {case["name"]} {case["block"]} step {step}: {json.dumps(case["steps"][step] if step < len(case["steps"]) else None)}') + print(f' vanilla: {(a or "")[:500]}') + print(f' horizon: {(b or "")[:500]}') + for kind, (ok, n) in sorted(kinds.items()): + print(f'{kind}: {ok}/{n} cases match') + passed = sum(ok for ok, _ in kinds.values()) + print(f'{passed}/{len(chosen)} cases match ({steps} ticked steps)') + if failures or errors: + sys.exit(1) + print('block entity animation parity ok') + + +if __name__ == '__main__': + main() From 0410a222ea95c686855e8179683d1ba31c3838ad Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:24:03 +0200 Subject: [PATCH 02/43] WIP: unfinished hud parity work, stopped for the night Uncommitted changes the agent had in progress when it was stopped; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/bossbar.rs | 4 +- crates/horizon-client/src/command/args.rs | 64 +- crates/horizon-client/src/fastutil_order.rs | 148 ++++ crates/horizon-client/src/game.rs | 16 +- crates/horizon-client/src/game/chat.rs | 11 +- .../src/game/command_harness.rs | 123 +++ crates/horizon-client/src/game/commands.rs | 77 +- .../src/game/commands/execute.rs | 6 + .../horizon-client/src/game/commands/extra.rs | 834 ++++++++++++++++++ crates/horizon-client/src/game/game_mode.rs | 5 + crates/horizon-client/src/game/lan.rs | 14 +- crates/horizon-client/src/game/lan_actions.rs | 7 +- crates/horizon-client/src/game/lan_screen.rs | 2 +- crates/horizon-client/src/lang.rs | 32 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/scoreboard.rs | 35 +- crates/horizon-client/src/scoreboard_cmd.rs | 5 +- crates/horizon-client/src/worldborder.rs | 4 +- .../parity/VanillaCommandExecOracle.java | 367 ++++++++ tools/command_exec_corpus.py | 339 +++++++ tools/prepare_native_client.py | 18 + tools/test_command_exec_parity.py | 158 ++++ 22 files changed, 2237 insertions(+), 33 deletions(-) create mode 100644 crates/horizon-client/src/fastutil_order.rs create mode 100644 crates/horizon-client/src/game/command_harness.rs create mode 100644 crates/horizon-client/src/game/commands/extra.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java create mode 100644 tools/command_exec_corpus.py create mode 100644 tools/test_command_exec_parity.py diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index 9df17431c..a976258f9 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -57,7 +57,9 @@ impl BossBar { hover: Some(Box::new(Text::literal(self.id.clone()))), ..Style::default() }; - bracketed(comp_text(&self.name).with_style(&style)) + // ComponentUtils.wrapInSquareBrackets(name).withStyle(...): the + // brackets take the colour too. + bracketed(comp_text(&self.name)).with_style(&style) } /// The filled fraction of the bar (`BossEvent.getProgress`). pub fn progress(&self) -> f32 { diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 1f24bfbf6..32208fa20 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -83,6 +83,67 @@ pub struct RegistryIds { } const EMPTY: &[String] = &[]; impl Registries { + /// Fill what the game did not build itself from vanilla's exported + /// registries (`command-registries.json`, written by + /// `VanillaCommandParseOracle registries`): built-in registries such as + /// mob effects, data component types and dialogs, block entities and tag + /// members. Registries that data packs reload stay with the game. + pub fn fill_from_export(&mut self, r: &serde_json::Value) { + fn strings(v: &serde_json::Value) -> Vec { + v.as_array() + .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()) + .unwrap_or_default() + } + let fill = |field: &mut Vec, key: &str| { + if field.is_empty() { + *field = strings(&r[key]); + } + }; + fill(&mut self.effects, "effects"); + fill(&mut self.enchantments, "enchantments"); + fill(&mut self.attributes, "attributes"); + fill(&mut self.damage_types, "damage_types"); + fill(&mut self.templates, "templates"); + fill(&mut self.persistent_components, "persistent_components"); + fill(&mut self.learnable_recipes, "learnable_recipes"); + const RELOADED: [&str; 5] = [ + "minecraft:advancement", + "minecraft:recipe", + "minecraft:loot_table", + "minecraft:predicate", + "minecraft:item_modifier", + ]; + for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { + if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { + continue; + } + self.by_registry.insert( + name.clone(), + RegistryIds { + ids: strings(&entry["ids"]), + tags: strings(&entry["tags"]), + }, + ); + } + if self.block_entities.is_empty() { + self.block_entities = strings(&r["block_entities"]).into_iter().collect(); + } + if self.block_tag_members.is_empty() { + for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { + self.block_tag_members.insert(tag.clone(), strings(members)); + } + } + if self.clock_time_markers.is_empty() { + for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { + self.clock_time_markers.insert(clock.clone(), strings(markers)); + } + } + if self.advancement_criteria.is_empty() { + for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { + self.advancement_criteria.insert(id.clone(), strings(criteria)); + } + } + } /// The element ids of a registry (sorted). pub fn ids(&self, registry: &str) -> &[String] { if let Some(r) = self.by_registry.get(registry) { @@ -1539,7 +1600,8 @@ impl ArgType { if block { parse_coord_int(reader) } else { - parse_coord_double(reader, false) + // Vec2Argument.vec2(): integers are centred on the block. + parse_coord_double(reader, true) } }; let x = one(reader)?; diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client/src/fastutil_order.rs new file mode 100644 index 000000000..d833d44dd --- /dev/null +++ b/crates/horizon-client/src/fastutil_order.rs @@ -0,0 +1,148 @@ +//! Iteration order of fastutil's `Object2ObjectOpenHashMap` (open +//! addressing with linear probing, backward-shift deletion and rehashing at +//! the load factor), for the vanilla collections whose order commands show: +//! the scoreboard's objectives and teams. + +/// The keys of an open hash map in their table slots. +#[derive(Clone, Debug, PartialEq)] +pub struct OpenOrder { + keys: Vec>, + size: usize, + min_n: usize, + load: f32, +} +impl Default for OpenOrder { + /// `new Object2ObjectOpenHashMap<>()`: 16 expected entries, load 0.75. + fn default() -> Self { + Self::new(16, 0.75) + } +} +/// `String.hashCode`. +fn java_hash(s: &str) -> i32 { + s.encode_utf16() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))) +} +/// `HashCommon.mix`. +fn mix(x: i32) -> usize { + let h = (x as u32).wrapping_mul(0x9E37_79B9); + (h ^ (h >> 16)) as usize +} +/// `HashCommon.arraySize`. +fn array_size(expected: usize, f: f32) -> usize { + let wanted = (expected as f64 / f64::from(f)).ceil() as usize; + wanted.max(2).next_power_of_two() +} +impl OpenOrder { + pub fn new(expected: usize, load: f32) -> Self { + let n = array_size(expected, load); + Self { + keys: vec![None; n], + size: 0, + min_n: n, + load, + } + } + fn max_fill(&self) -> usize { + ((self.keys.len() as f64 * f64::from(self.load)).ceil() as usize).min(self.keys.len() - 1) + } + fn slot(&self, key: &str) -> usize { + mix(java_hash(key)) & (self.keys.len() - 1) + } + pub fn insert(&mut self, key: &str) { + let mask = self.keys.len() - 1; + let mut pos = self.slot(key); + while let Some(k) = &self.keys[pos] { + if k == key { + return; + } + pos = (pos + 1) & mask; + } + self.keys[pos] = Some(key.to_owned()); + self.size += 1; + if self.size >= self.max_fill() { + self.rehash(array_size(self.size + 1, self.load)); + } + } + pub fn remove(&mut self, key: &str) { + let mask = self.keys.len() - 1; + let mut pos = self.slot(key); + loop { + match &self.keys[pos] { + None => return, + Some(k) if k == key => break, + Some(_) => pos = (pos + 1) & mask, + } + } + self.size -= 1; + self.shift_keys(pos); + let n = self.keys.len(); + if n > self.min_n && self.size < self.max_fill() / 4 && n > 16 { + self.rehash(n / 2); + } + } + fn shift_keys(&mut self, mut pos: usize) { + let mask = self.keys.len() - 1; + loop { + let last = pos; + pos = (last + 1) & mask; + loop { + let Some(curr) = self.keys[pos].clone() else { + self.keys[last] = None; + return; + }; + let slot = self.slot(&curr); + let stop = if last <= pos { + last >= slot || slot > pos + } else { + last >= slot && slot > pos + }; + if stop { + self.keys[last] = Some(curr); + break; + } + pos = (pos + 1) & mask; + } + } + } + fn rehash(&mut self, new_n: usize) { + let old = std::mem::replace(&mut self.keys, vec![None; new_n]); + let mask = new_n - 1; + for key in old.into_iter().rev().flatten() { + let mut pos = mix(java_hash(&key)) & mask; + while self.keys[pos].is_some() { + pos = (pos + 1) & mask; + } + self.keys[pos] = Some(key); + } + } + /// The iteration order (`keySet().iterator()`: from the last slot down). + pub fn keys(&self) -> impl Iterator { + self.keys.iter().rev().flatten().map(String::as_str) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hash_and_order() { + assert_eq!(java_hash("harness"), "harness".chars().fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))); + let mut o = OpenOrder::new(16, 0.5); + for k in ["harness", "harness_h"] { + o.insert(k); + } + let keys: Vec<&str> = o.keys().collect(); + assert_eq!(keys.len(), 2); + o.remove("harness"); + assert_eq!(o.keys().collect::>(), vec!["harness_h"]); + for i in 0..40 { + o.insert(&format!("k{i}")); + } + assert_eq!(o.keys().count(), 41); + for i in 0..40 { + o.remove(&format!("k{i}")); + } + assert_eq!(o.keys().collect::>(), vec!["harness_h"]); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..7ff2ae3ef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -14,6 +14,7 @@ mod breezes; mod cartography; mod chat; mod combat; +mod command_harness; mod commands; mod control; mod creaking; @@ -733,7 +734,9 @@ struct Game<'a> { lan_events: Vec<(i32, [i32; 3], i32, Option)>, lan_acting: Option, /// Command feedback to forward to a guest. - chat_capture: Option>, + chat_capture: Option>, + /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. + cmds: commands::extra::CommandExtras, /// Allow Cheats: whether guests may be given commands. cheats: bool, ui: chat::UiState, @@ -2470,6 +2473,8 @@ impl Game<'_> { } self.apply_totem(); self.update_totem_ready(); + self.tick_command_extras(); + let camera_eye = self.camera_eye_height(); if self.riding.is_some() && self.player.is_some() { let playing = self.screen == Screen::Playing; let held = |k| playing && self.keys.contains(&k); @@ -2560,7 +2565,7 @@ impl Game<'_> { } let feet = [player.position.x, player.position.y, player.position.z]; self.previous_eye = self.eye; - self.eye += (player.dimensions.eye_height - self.eye) * 0.5; + self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.record_combat(&events); for event in events { @@ -8611,6 +8616,7 @@ pub fn run() -> Result<()> { lan_events: Vec::new(), lan_acting: None, chat_capture: None, + cmds: Default::default(), cheats: true, ui: Default::default(), combat: Default::default(), @@ -8655,6 +8661,12 @@ pub fn run() -> Result<()> { } None => game.title = Some(Title::new(std::env::current_dir()?.join("saves"))), } + if let (Some(script), Some(output)) = ( + std::env::var_os("HORIZON_COMMAND_SCRIPT"), + std::env::var_os("HORIZON_COMMAND_OUTPUT"), + ) { + return game.run_command_harness(script.as_ref(), output.as_ref()); + } EventLoop::new()?.run_app(&mut game)?; if let Some(path) = &game.options.report { let report = serde_json::json!({ diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 812ac6118..816c8831f 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -324,6 +324,15 @@ impl Game<'_> { ); } } + // Vanilla's built-in registries (mob effects, components, dialogs...). + for dir in [&self.options.resources, &self.ui.vanilla_root] { + if let Ok(bytes) = std::fs::read(dir.join("command-registries.json")) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + self.ui.registries.fill_from_export(&v); + break; + } + } let reg = &mut self.ui.registries; reg.timelines = self.ui.timelines.keys().cloned().collect(); reg.time_markers = self @@ -368,7 +377,7 @@ impl Game<'_> { /// A chat message from the game (ChatComponent.addServerSystemMessage). pub(super) fn system_message(&mut self, text: Text) { if let Some(capture) = self.chat_capture.as_mut() { - capture.push(text.plain()); + capture.push(text); return; } let focused = self.screen == Screen::Chat; diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs new file mode 100644 index 000000000..ce18149f4 --- /dev/null +++ b/crates/horizon-client/src/game/command_harness.rs @@ -0,0 +1,123 @@ +//! Headless command runner for `tools/test_command_exec_parity.py`: with +//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world +//! runs without a window. Each script line is a JSON operation: `cmd` runs a +//! command as the player (Commands.performPrefixedCommand) and records every +//! system message it produced, as styled spans, with the results reported to +//! the player's `CommandResultCallback`; `tick` advances the game; `settle` +//! waits until the terrain around the player is loaded. +use super::Game; +use horizon_client::{Result, text::Text}; +use serde_json::{Value, json}; +use std::{ + path::Path, + time::{Duration, Instant}, +}; + +/// A message as `[text, style]` runs with adjacent equal styles merged; the +/// style lists colour, bold, italic, underlined, strikethrough, obfuscated +/// and the suggested command. +pub(super) fn spans(text: &Text) -> Value { + let mut out: Vec<(String, Value)> = Vec::new(); + for span in &text.spans { + if span.text.is_empty() { + continue; + } + let s = &span.style; + let style = json!([ + s.color, + s.bold == Some(true), + s.italic == Some(true), + s.underlined == Some(true), + s.strikethrough == Some(true), + s.obfuscated == Some(true), + ]); + match out.last_mut() { + Some((t, last)) if *last == style => t.push_str(&span.text), + _ => out.push((span.text.clone(), style)), + } + } + Value::Array(out.into_iter().map(|(t, s)| json!([t, s])).collect()) +} + +impl Game<'_> { + /// Load terrain until the player stands in lit chunks. + fn harness_settle(&mut self, deadline: Instant) -> Result<()> { + loop { + self.update_world(); + self.spawn_player()?; + if let Some(p) = &self.player { + let (cx, cz) = ( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + ); + if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return Ok(()); + } + } + if std::env::var_os("HORIZON_HARNESS_DEBUG").is_some() && self.ticks % 1 == 0 { + eprintln!( + "settle: player {:?} center {:?} chunks {} pending {}", + self.player.as_ref().map(|p| p.position), + self.streaming.center, + self.world.chunks.len(), + self.streaming.pending() + ); + } + if Instant::now() > deadline { + return Err("command harness: terrain did not load".into()); + } + std::thread::sleep(Duration::from_millis(2)); + } + } + pub(super) fn run_command_harness(&mut self, script: &Path, output: &Path) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(std::env::var("HORIZON_HARNESS_TIMEOUT").ok().and_then(|v| v.parse().ok()).unwrap_or(600)); + self.harness_settle(deadline)?; + let mut out = String::new(); + for line in std::fs::read_to_string(script)?.lines() { + if line.trim().is_empty() { + continue; + } + let op: Value = serde_json::from_str(line)?; + match op["op"].as_str().unwrap_or("") { + "cmd" => { + let command = op["cmd"].as_str().unwrap_or(""); + self.chat_capture = Some(Vec::new()); + self.cmds.results = Some(Vec::new()); + self.run_command(command.strip_prefix('/').unwrap_or(command)); + let messages = self.chat_capture.take().unwrap_or_default(); + let results = self.cmds.results.take().unwrap_or_default(); + if op["record"].as_bool() != Some(false) { + let record = json!({ + "cmd": command, + "messages": messages.iter().map(spans).collect::>(), + "results": results.iter().map(|(s, v)| json!([s, v])).collect::>(), + }); + out.push_str(&record.to_string()); + out.push('\n'); + } + } + "tick" => { + self.chat_capture = Some(Vec::new()); + for _ in 0..op["n"].as_u64().unwrap_or(1) { + self.update_world(); + self.tick()?; + } + let messages = self.chat_capture.take().unwrap_or_default(); + if op["record"].as_bool() == Some(true) { + let record = json!({ + "cmd": "#tick", + "messages": messages.iter().map(spans).collect::>(), + "results": [], + }); + out.push_str(&record.to_string()); + out.push('\n'); + } + } + "settle" => self.harness_settle(deadline)?, + other => return Err(format!("command harness: unknown op {other}").into()), + } + } + std::fs::write(output, out)?; + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 9dfed52ea..0d91e0984 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -3,6 +3,7 @@ mod data; mod effects; pub(super) mod execute; +pub(super) mod extra; mod items; mod misc; mod place; @@ -283,7 +284,11 @@ impl Game<'_> { /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { - Target::Player => Text::literal(PLAYER_NAME), + Target::Player => match self.score.board.players_team(PLAYER_NAME) { + // PlayerTeam.formatNameForTeam. + Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)), + None => Text::literal(PLAYER_NAME), + }, Target::Item(id) => { let item = self .dropped @@ -537,6 +542,17 @@ impl Game<'_> { "clear" => self.cmd_clear(ctx), "item" => self.cmd_item(ctx), "item.modify" => self.cmd_item_modify(ctx), + "spectate" => self.cmd_spectate(ctx), + id if id.starts_with("waypoint.") => self.cmd_waypoint(id, ctx), + id if id.starts_with("dialog.") => self.cmd_dialog(id, ctx), + id if id.starts_with("posteffect.") => self.cmd_posteffect(id, ctx), + "kick" => self.cmd_kick(ctx), + "fetchprofile" => self.cmd_fetchprofile(ctx), + "publish" => self.cmd_publish(ctx), + "unpublish" => self.cmd_unpublish(), + "debug" => self.cmd_debug(ctx), + "jfr" => self.cmd_jfr(ctx), + "version" => self.cmd_version(), "place" => self.cmd_place(ctx), "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), @@ -583,7 +599,7 @@ impl Game<'_> { "commands.list.nameAndId", &[ Text::literal(PLAYER_NAME), - Text::literal("00000000-0000-0000-0000-000000000000"), + Text::literal(self.player_uuid_string()), ], ) } else { @@ -655,16 +671,23 @@ impl Game<'_> { } count += 1; let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); - if ctx.get("target").is_none() { + // GameModeCommand.logGamemodeChange: the source's own entity. + let own = match self.command_source { + None => true, + Some(s) => s.entity == Some(t), + }; + if own { self.feedback(Text::translate( "commands.gamemode.success.self", &[mode_name], )); } else { - self.system_message(Text::translate( - "gameMode.changed", - std::slice::from_ref(&mode_name), - )); + if self.ui.rules.bool("send_command_feedback") { + self.system_message(Text::translate( + "gameMode.changed", + std::slice::from_ref(&mode_name), + )); + } self.feedback(Text::translate( "commands.gamemode.success.other", &[Text::literal(PLAYER_NAME), mode_name], @@ -687,6 +710,15 @@ impl Game<'_> { .append("]") .with_color(color) } + /// ItemStack.getDisplayName of a renamed stack: the name in italics. + pub(super) fn item_display_name_custom(&self, item: &str, custom: &str) -> Text { + let color = self.item_display_name(item).spans.first().and_then(|s| s.style.color); + let mut t = Text::translate("chat.square_brackets", &[Text::literal(custom).italic()]); + if let Some(c) = color { + t = t.with_color(c); + } + t + } fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -757,7 +789,10 @@ impl Game<'_> { } } } - let name = self.item_display_name(&id); + let name = match extra.as_ref().and_then(|e| e.custom_name.clone()) { + Some(custom) => self.item_display_name_custom(&id, &custom), + None => self.item_display_name(&id), + }; let message = if targets.len() == 1 { Text::translate( "commands.give.success.single", @@ -1119,7 +1154,7 @@ impl Game<'_> { w.raining = raining; w.thundering = thundering; self.feedback(Text::translate(key, &[])); - Ok(duration.unwrap_or(0)) + Ok(duration.unwrap_or(-1)) } fn kill_target(&mut self, t: Target) { match t { @@ -1499,21 +1534,29 @@ impl Game<'_> { dest[2] + z - min[2], ], s, + self.world.block_entities.get(&(x, y, z)).cloned(), )); } } } if moving { - for (from, _, _) in &copies { + for (from, _, _, _) in &copies { self.place_state(*from, air, true)?; } } let strict = ctx.has("strict"); + // CloneCommands.clone sets every destination to a barrier first, so + // each copied state but a barrier counts as placed. + let barrier = self.res.assets.registry.default_state("minecraft:barrier"); let mut count = 0; - for (_, to, s) in copies { - if self.place_state(to, s, strict)? { + for (_, to, s, entity) in copies { + self.place_state(to, s, strict)?; + if Some(s) != barrier { count += 1; } + if let Some(e) = entity { + self.world.block_entities.insert((to[0], to[1], to[2]), e); + } } if count == 0 { return Err(err("commands.clone.failed", &[])); @@ -1760,7 +1803,7 @@ impl Game<'_> { if self.ui.difficulty == i { return Err(CommandError::new(Text::translate( "commands.difficulty.failure", - &[Text::literal(DIFFICULTIES[i as usize])], + &[name(i)], ))); } self.ui.difficulty = i; @@ -1810,7 +1853,7 @@ impl Game<'_> { dim, ]; let key = if targets.len() == 1 { - args.push(Text::literal(PLAYER_NAME)); + args.push(self.target_name(targets[0])); "commands.spawnpoint.success.single" } else { args.push(Text::literal(targets.len().to_string())); @@ -1830,9 +1873,6 @@ impl Game<'_> { p[2].floor() as i32, ] }; - if self.dim != Dim::Overworld { - return Err(err("commands.setworldspawn.failure.not_overworld", &[])); - } let rot = match ctx.get("rotation") { Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), _ => [0.0, 0.0], @@ -2128,6 +2168,9 @@ impl Game<'_> { .italic() } }; + if let Some(capture) = self.chat_capture.as_mut() { + capture.push(line.clone()); + } let focused = self.screen == Screen::Chat; self.ui .chat diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 2fda44bfe..fd715fd5d 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -189,6 +189,12 @@ impl Game<'_> { } /// `CommandResultCallback`s of a source's `store` chain, oldest first. fn deliver(&mut self, store: Option, success: bool, value: i32) { + // The outermost source's own CommandResultCallback (harness record). + if self.exec.function_depth == 0 + && let Some(results) = self.cmds.results.as_mut() + { + results.push((success, value)); + } let mut chain = Vec::new(); let mut at = store; while let Some(i) = at { diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs new file mode 100644 index 000000000..6184cb7f6 --- /dev/null +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -0,0 +1,834 @@ +//! Commands that act on the player and the hosted game rather than the world: +//! `/spectate` (SpectateCommand), `/waypoint` (WaypointCommand), `/dialog` +//! (DialogCommand), `/posteffect` (PostEffectCommand), `/kick`, +//! `/fetchprofile`, `/publish`, `/unpublish`, `/debug`, `/jfr` and +//! `/version`, with vanilla's feedback and failures. +use super::{Arg, Context, Game, R, Target, err}; +use horizon_client::{ + command::CommandError, + text::{self, Style, Text}, +}; +use std::{collections::HashMap, time::Instant}; + +/// Waypoint.Icon: the locator bar style and colour of a transmitter. +#[derive(Clone, Debug, PartialEq)] +pub(in crate::game) struct WaypointIcon { + pub style: String, + pub color: Option, +} +impl Default for WaypointIcon { + fn default() -> Self { + Self { + style: "minecraft:default".into(), + color: None, + } + } +} + +/// Server-side player and server state these commands keep. +#[derive(Default)] +pub(in crate::game) struct CommandExtras { + /// ServerPlayer.camera: the entity `/spectate` attached the view to. + pub camera: Option, + /// ServerPlayer.postEffects, in insertion order. + pub post_effects: Vec, + /// MinecraftServer's tick profiler (`/debug start`): when it started and + /// the tick count then. + pub profiler: Option<(Instant, u64)>, + /// `debugCommandProfilerDelayStart`: the profiler starts with the next tick. + pub profiler_delay: bool, + /// Messages the server sends on a later tick (profile lookups). + pub pending: Vec, + /// The `/jfr start` recording: when it started and the tick count then. + pub jfr: Option<(Instant, u64, String)>, + /// Waypoint icons changed by `/waypoint modify`. + pub waypoint_icons: HashMap, + /// The dialog `/dialog show` opened (its id or inline definition). + pub dialog: Option, + /// The `CommandResultCallback` results of the outermost source, when a + /// harness records them. + pub results: Option>, +} + +/// `version.json` of the 26.3 jars. +const VERSION_ID: &str = "26.3"; +const DATA_VERSION: i32 = 5023; +const STABLE: bool = true; +/// `Date.toString()` of the build time in UTC. +const BUILD_TIME: &str = "Tue Sep 15 11:20:48 UTC 2026"; + +fn num(n: impl std::fmt::Display) -> Text { + Text::literal(n.to_string()) +} +fn tr_error(key: &str, args: &[Text]) -> CommandError { + CommandError::new(Text::translate(key, args)) +} +/// `String.format(Locale.ROOT, "%.2f", v)`. +fn two_places(v: f64) -> String { + format!("{v:.2}") +} +/// `Util.getFilenameFormattedDateTime` (`yyyy-MM-dd_HH.mm.ss`, local time). +fn filename_date_time() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64); + let (y, mo, d, h, mi, s) = civil(secs); + format!("{y:04}-{mo:02}-{d:02}_{h:02}.{mi:02}.{s:02}") +} +/// UTC civil date and time of a Unix timestamp. +fn civil(secs: i64) -> (i64, i64, i64, i64, i64, i64) { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + (y, m, d, rem / 3600, rem % 3600 / 60, rem % 60) +} + +impl Game<'_> { + /// CommandSourceStack.getPlayerOrException. + fn source_player(&self) -> R { + match self.command_source.map(|s| s.entity) { + None | Some(Some(Target::Player)) => Ok(Target::Player), + _ => Err(err("permissions.requires.player", &[])), + } + } + /// EntityArgument.getEntity / getPlayer. + fn one_entity(&mut self, ctx: &Context, name: &str, player: bool) -> R { + Ok(self.entities(ctx, name, player)?[0]) + } + + // ---- /spectate ------------------------------------------------------ + + /// `SpectateCommand.spectate`. + pub(super) fn cmd_spectate(&mut self, ctx: &Context) -> R { + let target = if ctx.get("target").is_some() { + Some(self.one_entity(ctx, "target", false)?) + } else { + None + }; + let player = if ctx.get("player").is_some() { + self.one_entity(ctx, "player", true)? + } else { + self.source_player()? + }; + if target == Some(player) { + return Err(err("commands.spectate.self", &[])); + } + if !self.spectator() { + return Err(tr_error( + "commands.spectate.not_spectator", + &[self.target_name(player)], + )); + } + self.set_camera(target); + match target { + Some(t) => { + let name = self.target_name(t); + self.feedback(Text::translate("commands.spectate.success.started", &[name])); + } + None => self.feedback(Text::translate("commands.spectate.success.stopped", &[])), + } + Ok(1) + } + /// `ServerPlayer.setCamera`: a new camera moves the player to it. + pub(in crate::game) fn set_camera(&mut self, target: Option) { + let target = target.filter(|t| *t != Target::Player); + if self.cmds.camera == target { + return; + } + self.cmds.camera = target; + if let Some(t) = target + && let Some(p) = self.target_position(t) + && let Some(player) = self.player.as_mut() + { + player.position = horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + self.previous_position = player.position; + } + } + /// Per-tick server work of these commands: the delayed tick profiler + /// start, queued messages and the spectator camera. + pub(in crate::game) fn tick_command_extras(&mut self) { + if self.cmds.profiler_delay { + self.cmds.profiler_delay = false; + self.cmds.profiler = Some((Instant::now(), self.ticks)); + } + for message in std::mem::take(&mut self.cmds.pending) { + self.system_message(message); + } + self.tick_camera(); + } + /// The camera part of `ServerPlayer.tick`: follow a living camera, drop a + /// removed one, and stop when the player sneaks or leaves spectator mode. + fn tick_camera(&mut self) { + let Some(t) = self.cmds.camera else { + return; + }; + if !self.spectator() { + self.set_camera(None); + return; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) + && self.screen == super::Screen::Playing; + match self.target_position(t) { + Some(p) if !sneaking => { + let rot = self.target_rotation(t); + if let Some(player) = self.player.as_mut() { + player.position = horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + } + self.yaw = rot[0]; + self.pitch = rot[1]; + } + _ => self.set_camera(None), + } + } + /// The eye height the camera follows (`Camera.tick`'s entity). + pub(in crate::game) fn camera_eye_height(&self) -> Option { + self.cmds + .camera + .map(|t| self.target_eye_height(t) as f32) + } + + // ---- /waypoint ------------------------------------------------------ + + /// `ServerWaypointManager.transmitters()`: living entities whose + /// `waypoint_transmit_range` is positive. + fn waypoint_transmitters(&mut self) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.player.as_mut() + && let Some(k) = p.attributes.key("minecraft:waypoint_transmit_range") + && p.attributes + .value(Some(k), horizon_world::attribute_map::ValueKind::Computed) + .is_ok_and(|v| v > 0.0) + { + out.push(Target::Player); + } + out + } + fn waypoint_icon(&self, t: Target) -> WaypointIcon { + self.cmds.waypoint_icons.get(&t).cloned().unwrap_or_default() + } + /// `WaypointArgument.getWaypoint`. + fn waypoint_arg(&mut self, ctx: &Context) -> R { + let t = self.one_entity(ctx, "waypoint", false)?; + if !self.is_living(t) { + return Err(err("argument.waypoint.invalid", &[])); + } + Ok(t) + } + fn is_living(&self, t: Target) -> bool { + matches!(t, Target::Player | Target::Mob(_) | Target::Stand(_)) + } + pub(super) fn cmd_waypoint(&mut self, id: &str, ctx: &Context) -> R { + if id == "waypoint.list" { + let dimension = self.dim.id(); + let waypoints = self.waypoint_transmitters(); + if waypoints.is_empty() { + self.feedback(Text::translate( + "commands.waypoint.list.empty", + &[Text::literal(dimension)], + )); + return Ok(0); + } + let mut names = Text::empty(); + for (i, t) in waypoints.iter().enumerate() { + if i > 0 { + names.push(", "); + } + let pos = self + .target_position(*t) + .unwrap_or_default() + .map(|v| v.floor() as i32); + let color = self.waypoint_icon(*t).color.unwrap_or(-1) as u32 & 0xFF_FFFF; + let style = Style { + color: Some(color), + suggest: Some(format!( + "/execute in {dimension} run tp @s {} {} {}", + pos[0], pos[1], pos[2] + )), + hover: Some(Box::new(Text::translate("chat.coordinates.tooltip", &[]))), + ..Style::default() + }; + // getFeedbackDisplayName().copy().withStyle(color): the + // waypoint colour replaces the team colour of the name. + let name = match (*t, self.score.board.players_team(super::super::chat::PLAYER_NAME)) { + (Target::Player, Some(team)) => { + let mut n = Text::empty(); + n.push(horizon_client::scoreboard::comp_text(&team.prefix)); + n.push(super::super::chat::PLAYER_NAME); + n.push(horizon_client::scoreboard::comp_text(&team.suffix)); + n + } + _ => self.target_name(*t), + }; + names.push(name.with_style(&style)); + } + let n = waypoints.len() as i32; + self.feedback(Text::translate( + "commands.waypoint.list.success", + &[num(n), Text::literal(dimension), names], + )); + return Ok(n); + } + let t = self.waypoint_arg(ctx)?; + let mut icon = self.waypoint_icon(t); + let style_literal = ctx.literals.iter().any(|l| l == "style"); + let message = if style_literal { + icon.style = if ctx.literals.iter().any(|l| l == "reset") { + "minecraft:default".into() + } else { + match ctx.get("style") { + Some(Arg::Resource(s)) => s.clone(), + _ => "minecraft:default".into(), + } + }; + Text::translate("commands.waypoint.modify.style", &[]) + } else if ctx.literals.iter().any(|l| l == "reset") { + icon.color = None; + Text::translate("commands.waypoint.modify.color.reset", &[]) + } else if ctx.literals.iter().any(|l| l == "hex") { + let rgb = match ctx.get("color") { + Some(Arg::Int(v)) => *v, + _ => 0, + }; + icon.color = Some(rgb); + let hex = format!("{:06X}", rgb as u32 & 0xFF_FFFF); + Text::translate( + "commands.waypoint.modify.color", + &[Text::colored(hex, rgb as u32 & 0xFF_FFFF)], + ) + } else { + let name = match ctx.get("color") { + Some(Arg::Str(s)) => s.clone(), + _ => "white".into(), + }; + let rgb = text::named_color(&name).unwrap_or(0xFF_FFFF); + icon.color = Some(rgb as i32); + Text::translate( + "commands.waypoint.modify.color", + &[Text::colored(name, rgb)], + ) + }; + self.cmds.waypoint_icons.insert(t, icon); + self.feedback(message); + Ok(0) + } + + // ---- /dialog -------------------------------------------------------- + + pub(super) fn cmd_dialog(&mut self, id: &str, ctx: &Context) -> R { + let targets = self.entities(ctx, "targets", true)?; + let n = targets.len() as i32; + if id == "dialog.show" { + let Some(Arg::Resource(dialog)) = ctx.get("dialog").cloned() else { + return Ok(0); + }; + self.open_dialog(&dialog)?; + } else { + self.close_dialog(); + } + let (single, multiple) = if id == "dialog.show" { + ("commands.dialog.show.single", "commands.dialog.show.multiple") + } else { + ("commands.dialog.clear.single", "commands.dialog.clear.multiple") + }; + let message = if n == 1 { + Text::translate(single, &[self.target_name(targets[0])]) + } else { + Text::translate(multiple, &[num(n)]) + }; + self.feedback(message); + Ok(n) + } + + // ---- /posteffect ---------------------------------------------------- + + pub(super) fn cmd_posteffect(&mut self, id: &str, ctx: &Context) -> R { + if id == "posteffect.list" { + let t = self.one_entity(ctx, "target", true)?; + let name = self.target_name(t); + let effects = self.cmds.post_effects.clone(); + if effects.is_empty() { + self.feedback(Text::translate("commands.posteffect.list.empty", &[name])); + } else { + self.feedback(Text::translate( + "commands.posteffect.list.success", + &[name, num(effects.len()), Text::literal(effects.join(", "))], + )); + } + return Ok(effects.len() as i32); + } + let targets = self.entities(ctx, "targets", true)?; + let effect = match ctx.get("posteffect") { + Some(Arg::Resource(s)) => s.clone(), + _ => String::new(), + }; + let mut changed: Vec = Vec::new(); + for t in &targets { + let done = match id { + "posteffect.add" => { + if self.cmds.post_effects.contains(&effect) { + false + } else { + self.cmds.post_effects.push(effect.clone()); + true + } + } + "posteffect.remove" => { + let before = self.cmds.post_effects.len(); + if let Some(i) = self.cmds.post_effects.iter().position(|e| *e == effect) { + self.cmds.post_effects.remove(i); + } + before != self.cmds.post_effects.len() + } + _ => !std::mem::take(&mut self.cmds.post_effects).is_empty(), + }; + if done { + changed.push(*t); + } + } + let key = id.trim_start_matches("posteffect."); + if changed.is_empty() { + return Err(err(&format!("commands.posteffect.{key}.failed"), &[])); + } + let n = changed.len() as i32; + let effect_text = Text::literal(effect); + let message = match (key, n) { + ("clear", 1) => Text::translate( + "commands.posteffect.clear.success.single", + &[self.target_name(changed[0])], + ), + ("clear", _) => Text::translate("commands.posteffect.clear.success.multiple", &[num(n)]), + (_, 1) => Text::translate( + &format!("commands.posteffect.{key}.success.single"), + &[effect_text, self.target_name(changed[0])], + ), + _ => Text::translate( + &format!("commands.posteffect.{key}.success.multiple"), + &[effect_text, num(n)], + ), + }; + self.feedback(message); + Ok(n) + } + + // ---- /kick ---------------------------------------------------------- + + /// `KickCommand.kickPlayers`: only guests of a published world can be + /// kicked; the owner never. + pub(super) fn cmd_kick(&mut self, ctx: &Context) -> R { + let selector = match ctx.get("targets") { + Some(Arg::Entity(s)) => Some(s.clone()), + _ => None, + }; + // EntityArgument.getPlayers runs before the published check. + let host = self.entities(ctx, "targets", true).unwrap_or_default(); + let guests: Vec<(u32, String)> = match (&self.lan, &selector) { + (Some(lan), Some(s)) => lan + .hub + .guests + .iter() + .filter(|g| match &s.player_name { + Some(name) => g.name.eq_ignore_ascii_case(name), + None => s.kind == 'a' || s.kind == 'e', + }) + .map(|g| (g.conn, g.name.clone())) + .collect(), + _ => Vec::new(), + }; + if host.is_empty() && guests.is_empty() { + return Err(err("argument.entity.notfound.player", &[])); + } + if self.lan.is_none() { + return Err(err("commands.kick.singleplayer.failed", &[])); + } + let reason_raw = match ctx.get("reason") { + Some(Arg::Str(s)) => Some(s.clone()), + _ => None, + }; + let reason = match &reason_raw { + Some(raw) => self.expand_selectors(raw), + None => Text::translate("multiplayer.disconnect.kicked", &[]), + }; + let tag = match &reason_raw { + Some(_) => horizon_world::nbt::Tag::String(reason.plain().as_str().into()), + None => horizon_world::nbt::Tag::compound([( + "translate", + horizon_world::nbt::Tag::String("multiplayer.disconnect.kicked".into()), + )]), + }; + let mut count = 0; + for (conn, name) in guests { + if let Some(lan) = self.lan.as_mut() { + lan.hub.kick(conn, tag.clone()); + } + self.feedback(Text::translate( + "commands.kick.success", + &[Text::literal(name), reason.clone()], + )); + count += 1; + } + if count == 0 { + return Err(err("commands.kick.owner.failed", &[])); + } + Ok(count) + } + + // ---- /fetchprofile -------------------------------------------------- + + /// `FetchProfileCommand`: Horizon resolves no profiles over the network, + /// so name and id lookups fail like an unreachable profile service; an + /// entity with a profile (the player) prints its resolved profile. + pub(super) fn cmd_fetchprofile(&mut self, ctx: &Context) -> R { + if ctx.literals.iter().any(|l| l == "name") { + let name = match ctx.get("name") { + Some(Arg::Str(s)) => s.clone(), + _ => String::new(), + }; + // Resolved off-thread; the answer arrives on a later tick. + self.cmds.pending.push( + Text::translate("commands.fetchprofile.name.failure", &[Text::literal(name)]) + .with_color(text::RED), + ); + return Ok(1); + } + if ctx.literals.iter().any(|l| l == "id") { + let id = match ctx.get("id") { + Some(Arg::Str(s)) => s.to_ascii_lowercase(), + _ => String::new(), + }; + self.cmds.pending.push( + Text::translate("commands.fetchprofile.id.failure", &[Text::literal(id)]) + .with_color(text::RED), + ); + return Ok(1); + } + let t = self.one_entity(ctx, "entity", false)?; + if t != Target::Player { + return Err(tr_error( + "commands.fetchprofile.no_profile", + &[self.target_name(t)], + )); + } + let profile = self.player_profile_snbt(); + let name = super::super::chat::PLAYER_NAME; + let head = format!("{{type:\"minecraft:player\",player:{profile}}}"); + let item = |key: &str, args: &[Text], run: Option| { + let inner = Text::translate(key, args).with_color(text::GREEN); + let mut t = Text::translate("chat.square_brackets", &[inner]); + if let Some(cmd) = run { + t = t.with_style(&Style { + suggest: None, + ..Style::default() + }); + let _ = cmd; + } + t + }; + let placeholder = Text::literal("\u{FFFC}").with_color(text::WHITE); + let mut clickable = item("commands.fetchprofile.copy_component", &[], None); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.give_item", + &[], + Some(format!("give @s minecraft:player_head[profile={profile}]")), + )); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.summon_mannequin", + &[], + Some(format!("summon minecraft:mannequin ~ ~ ~ {{profile:{profile}}}")), + )); + clickable.push(" "); + clickable.push(item("commands.fetchprofile.copy_text", &[placeholder], None)); + let _ = head; + self.feedback(Text::translate( + "commands.fetchprofile.entity.success", + &[Text::literal(name), clickable], + )); + Ok(1) + } + /// ResolvableProfile.CODEC of the player's profile as SNBT. + fn player_profile_snbt(&self) -> String { + let [a, b, c, d] = self.level.player_uuid.unwrap_or([0; 4]); + format!( + "{{id:[I;{a},{b},{c},{d}],name:\"{}\",properties:[]}}", + super::super::chat::PLAYER_NAME + ) + } + + // ---- /publish, /unpublish ------------------------------------------- + + /// `PublishCommand.publish` with `IntegratedServer.publishServer`. + pub(super) fn cmd_publish(&mut self, ctx: &Context) -> R { + let allow = matches!(ctx.get("allowCommands"), Some(Arg::Bool(true))); + let port = match ctx.get("port") { + Some(Arg::Int(p)) => *p, + // HttpUtil.getAvailablePort. + _ => std::net::TcpListener::bind(("0.0.0.0", 0)) + .and_then(|l| l.local_addr()) + .map_or(25564, |a| i32::from(a.port())), + }; + if let Some(lan) = &self.lan { + return Err(err( + "commands.publish.alreadyPublished.lan", + &[&lan.settings.port], + )); + } + let settings = super::super::lan::LanSettings { + port: port as u16, + guest_commands: allow, + force_game_mode: false, + }; + if self.lan_start(settings).is_err() { + return Err(err("commands.publish.failed", &[])); + } + let port_text = port.to_string(); + let link = Text::literal(port_text.clone()).with_style(&Style { + color: Some(text::GREEN), + hover: Some(Box::new(Text::translate("chat.copy.click", &[]))), + ..Style::default() + }); + self.feedback(Text::translate( + "commands.publish.started.lan", + &[Text::translate("chat.square_brackets", &[link])], + )); + Ok(port) + } + pub(super) fn cmd_unpublish(&mut self) -> R { + if self.lan.is_none() { + return Err(err("commands.unpublish.notPublished", &[])); + } + self.lan_close(false); + self.feedback(Text::translate("commands.unpublish.success", &[])); + Ok(1) + } + + // ---- /debug, /jfr, /version ----------------------------------------- + + pub(super) fn cmd_debug(&mut self, ctx: &Context) -> R { + if ctx.literals.iter().any(|l| l == "function") { + return self.cmd_debug_function(ctx); + } + // MinecraftServer.isTimeProfilerRunning / startTimeProfiler / + // stopTimeProfiler: a stop before the delayed start took effect + // reports empty results and leaves the start pending. + let running = self.cmds.profiler_delay || self.cmds.profiler.is_some(); + if ctx.literals.iter().any(|l| l == "start") { + if running { + return Err(err("commands.debug.alreadyRunning", &[])); + } + self.cmds.profiler_delay = true; + self.feedback(Text::translate("commands.debug.started", &[])); + return Ok(0); + } + if !running { + return Err(err("commands.debug.notRunning", &[])); + } + let (seconds, ticks) = match self.cmds.profiler.take() { + Some((started, ticks)) => ( + started.elapsed().as_nanos() as f64 / 1.0e9, + (self.ticks - ticks) as f64, + ), + None => (0.0, 0.0), + }; + let tps = ticks / seconds; + self.feedback(Text::translate( + "commands.debug.stopped", + &[ + Text::literal(two_places(seconds)), + num(ticks as i64), + Text::literal(two_places(tps)), + ], + )); + Ok(tps as i32) + } + /// `DebugCommand.TraceCustomExecutor`: run the functions with a tracer + /// writing to `debug/debug-trace-